]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/project.rs
Auto merge of #38268 - withoutboats:parse_where_higher_rank_hack, r=eddyb
[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::SelectionContext;
20 use super::SelectionError;
21 use super::VtableClosureData;
22 use super::VtableFnPointerData;
23 use super::VtableImplData;
24 use super::util;
25
26 use hir::def_id::DefId;
27 use infer::InferOk;
28 use infer::type_variable::TypeVariableOrigin;
29 use rustc_data_structures::snapshot_map::{Snapshot, SnapshotMap};
30 use syntax::ast;
31 use syntax::symbol::Symbol;
32 use ty::subst::Subst;
33 use ty::{self, ToPredicate, ToPolyTraitRef, Ty, TyCtxt};
34 use ty::fold::{TypeFoldable, TypeFolder};
35 use util::common::FN_OUTPUT_NAME;
36
37 /// Depending on the stage of compilation, we want projection to be
38 /// more or less conservative.
39 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
40 pub enum Reveal {
41     /// FIXME (#32205)
42     /// At coherence-checking time, we're still constructing the
43     /// specialization graph, and thus we only project
44     /// non-`default` associated types that are defined directly in
45     /// the applicable impl. (This behavior should be improved over
46     /// time, to allow for successful projections modulo cycles
47     /// between different impls).
48     ///
49     /// Here's an example that will fail due to the restriction:
50     ///
51     /// ```
52     /// trait Assoc {
53     ///     type Output;
54     /// }
55     ///
56     /// impl<T> Assoc for T {
57     ///     type Output = bool;
58     /// }
59     ///
60     /// impl Assoc for u8 {} // <- inherits the non-default type from above
61     ///
62     /// trait Foo {}
63     /// impl Foo for u32 {}
64     /// impl Foo for <u8 as Assoc>::Output {}  // <- this projection will fail
65     /// ```
66     ///
67     /// The projection would succeed if `Output` had been defined
68     /// directly in the impl for `u8`.
69     ExactMatch,
70
71     /// At type-checking time, we refuse to project any associated
72     /// type that is marked `default`. Non-`default` ("final") types
73     /// are always projected. This is necessary in general for
74     /// soundness of specialization. However, we *could* allow
75     /// projections in fully-monomorphic cases. We choose not to,
76     /// because we prefer for `default type` to force the type
77     /// definition to be treated abstractly by any consumers of the
78     /// impl. Concretely, that means that the following example will
79     /// fail to compile:
80     ///
81     /// ```
82     /// trait Assoc {
83     ///     type Output;
84     /// }
85     ///
86     /// impl<T> Assoc for T {
87     ///     default type Output = bool;
88     /// }
89     ///
90     /// fn main() {
91     ///     let <() as Assoc>::Output = true;
92     /// }
93     NotSpecializable,
94
95     /// At trans time, all monomorphic projections will succeed.
96     /// Also, `impl Trait` is normalized to the concrete type,
97     /// which has to be already collected by type-checking.
98     ///
99     /// NOTE: As `impl Trait`'s concrete type should *never*
100     /// be observable directly by the user, `Reveal::All`
101     /// should not be used by checks which may expose
102     /// type equality or type contents to the user.
103     /// There are some exceptions, e.g. around OIBITS and
104     /// transmute-checking, which expose some details, but
105     /// not the whole concrete type of the `impl Trait`.
106     All,
107 }
108
109 pub type PolyProjectionObligation<'tcx> =
110     Obligation<'tcx, ty::PolyProjectionPredicate<'tcx>>;
111
112 pub type ProjectionObligation<'tcx> =
113     Obligation<'tcx, ty::ProjectionPredicate<'tcx>>;
114
115 pub type ProjectionTyObligation<'tcx> =
116     Obligation<'tcx, ty::ProjectionTy<'tcx>>;
117
118 /// When attempting to resolve `<T as TraitRef>::Name` ...
119 #[derive(Debug)]
120 pub enum ProjectionTyError<'tcx> {
121     /// ...we found multiple sources of information and couldn't resolve the ambiguity.
122     TooManyCandidates,
123
124     /// ...an error occurred matching `T : TraitRef`
125     TraitSelectionError(SelectionError<'tcx>),
126 }
127
128 #[derive(Clone)]
129 pub struct MismatchedProjectionTypes<'tcx> {
130     pub err: ty::error::TypeError<'tcx>
131 }
132
133 #[derive(PartialEq, Eq, Debug)]
134 enum ProjectionTyCandidate<'tcx> {
135     // from a where-clause in the env or object type
136     ParamEnv(ty::PolyProjectionPredicate<'tcx>),
137
138     // from the definition of `Trait` when you have something like <<A as Trait>::B as Trait2>::C
139     TraitDef(ty::PolyProjectionPredicate<'tcx>),
140
141     // from a "impl" (or a "pseudo-impl" returned by select)
142     Select,
143 }
144
145 struct ProjectionTyCandidateSet<'tcx> {
146     vec: Vec<ProjectionTyCandidate<'tcx>>,
147     ambiguous: bool
148 }
149
150 /// Evaluates constraints of the form:
151 ///
152 ///     for<...> <T as Trait>::U == V
153 ///
154 /// If successful, this may result in additional obligations.
155 pub fn poly_project_and_unify_type<'cx, 'gcx, 'tcx>(
156     selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
157     obligation: &PolyProjectionObligation<'tcx>)
158     -> Result<Option<Vec<PredicateObligation<'tcx>>>, MismatchedProjectionTypes<'tcx>>
159 {
160     debug!("poly_project_and_unify_type(obligation={:?})",
161            obligation);
162
163     let infcx = selcx.infcx();
164     infcx.commit_if_ok(|snapshot| {
165         let (skol_predicate, skol_map) =
166             infcx.skolemize_late_bound_regions(&obligation.predicate, snapshot);
167
168         let skol_obligation = obligation.with(skol_predicate);
169         let r = match project_and_unify_type(selcx, &skol_obligation) {
170             Ok(result) => {
171                 let span = obligation.cause.span;
172                 match infcx.leak_check(false, span, &skol_map, snapshot) {
173                     Ok(()) => Ok(infcx.plug_leaks(skol_map, snapshot, result)),
174                     Err(e) => Err(MismatchedProjectionTypes { err: e }),
175                 }
176             }
177             Err(e) => {
178                 Err(e)
179             }
180         };
181
182         r
183     })
184 }
185
186 /// Evaluates constraints of the form:
187 ///
188 ///     <T as Trait>::U == V
189 ///
190 /// If successful, this may result in additional obligations.
191 fn project_and_unify_type<'cx, 'gcx, 'tcx>(
192     selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
193     obligation: &ProjectionObligation<'tcx>)
194     -> Result<Option<Vec<PredicateObligation<'tcx>>>, MismatchedProjectionTypes<'tcx>>
195 {
196     debug!("project_and_unify_type(obligation={:?})",
197            obligation);
198
199     let Normalized { value: normalized_ty, mut obligations } =
200         match opt_normalize_projection_type(selcx,
201                                             obligation.predicate.projection_ty.clone(),
202                                             obligation.cause.clone(),
203                                             obligation.recursion_depth) {
204             Some(n) => n,
205             None => return Ok(None),
206         };
207
208     debug!("project_and_unify_type: normalized_ty={:?} obligations={:?}",
209            normalized_ty,
210            obligations);
211
212     let infcx = selcx.infcx();
213     match infcx.eq_types(true, &obligation.cause, normalized_ty, obligation.predicate.ty) {
214         Ok(InferOk { obligations: inferred_obligations, value: () }) => {
215             obligations.extend(inferred_obligations);
216             Ok(Some(obligations))
217         },
218         Err(err) => Err(MismatchedProjectionTypes { err: err }),
219     }
220 }
221
222 /// Normalizes any associated type projections in `value`, replacing
223 /// them with a fully resolved type where possible. The return value
224 /// combines the normalized result and any additional obligations that
225 /// were incurred as result.
226 pub fn normalize<'a, 'b, 'gcx, 'tcx, T>(selcx: &'a mut SelectionContext<'b, 'gcx, 'tcx>,
227                                         cause: ObligationCause<'tcx>,
228                                         value: &T)
229                                         -> Normalized<'tcx, T>
230     where T : TypeFoldable<'tcx>
231 {
232     normalize_with_depth(selcx, cause, 0, value)
233 }
234
235 /// As `normalize`, but with a custom depth.
236 pub fn normalize_with_depth<'a, 'b, 'gcx, 'tcx, T>(
237     selcx: &'a mut SelectionContext<'b, 'gcx, 'tcx>,
238     cause: ObligationCause<'tcx>,
239     depth: usize,
240     value: &T)
241     -> Normalized<'tcx, T>
242
243     where T : TypeFoldable<'tcx>
244 {
245     debug!("normalize_with_depth(depth={}, value={:?})", depth, value);
246     let mut normalizer = AssociatedTypeNormalizer::new(selcx, cause, depth);
247     let result = normalizer.fold(value);
248     debug!("normalize_with_depth: depth={} result={:?} with {} obligations",
249            depth, result, normalizer.obligations.len());
250     debug!("normalize_with_depth: depth={} obligations={:?}",
251            depth, normalizer.obligations);
252     Normalized {
253         value: result,
254         obligations: normalizer.obligations,
255     }
256 }
257
258 struct AssociatedTypeNormalizer<'a, 'b: 'a, 'gcx: 'b+'tcx, 'tcx: 'b> {
259     selcx: &'a mut SelectionContext<'b, 'gcx, 'tcx>,
260     cause: ObligationCause<'tcx>,
261     obligations: Vec<PredicateObligation<'tcx>>,
262     depth: usize,
263 }
264
265 impl<'a, 'b, 'gcx, 'tcx> AssociatedTypeNormalizer<'a, 'b, 'gcx, 'tcx> {
266     fn new(selcx: &'a mut SelectionContext<'b, 'gcx, 'tcx>,
267            cause: ObligationCause<'tcx>,
268            depth: usize)
269            -> AssociatedTypeNormalizer<'a, 'b, 'gcx, 'tcx>
270     {
271         AssociatedTypeNormalizer {
272             selcx: selcx,
273             cause: cause,
274             obligations: vec![],
275             depth: depth,
276         }
277     }
278
279     fn fold<T:TypeFoldable<'tcx>>(&mut self, value: &T) -> T {
280         let value = self.selcx.infcx().resolve_type_vars_if_possible(value);
281
282         if !value.has_projection_types() {
283             value.clone()
284         } else {
285             value.fold_with(self)
286         }
287     }
288 }
289
290 impl<'a, 'b, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for AssociatedTypeNormalizer<'a, 'b, 'gcx, 'tcx> {
291     fn tcx<'c>(&'c self) -> TyCtxt<'c, 'gcx, 'tcx> {
292         self.selcx.tcx()
293     }
294
295     fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
296         // We don't want to normalize associated types that occur inside of region
297         // binders, because they may contain bound regions, and we can't cope with that.
298         //
299         // Example:
300         //
301         //     for<'a> fn(<T as Foo<&'a>>::A)
302         //
303         // Instead of normalizing `<T as Foo<&'a>>::A` here, we'll
304         // normalize it when we instantiate those bound regions (which
305         // should occur eventually).
306
307         let ty = ty.super_fold_with(self);
308         match ty.sty {
309             ty::TyAnon(def_id, substs) if !substs.has_escaping_regions() => { // (*)
310                 // Only normalize `impl Trait` after type-checking, usually in trans.
311                 if self.selcx.projection_mode() == Reveal::All {
312                     let generic_ty = self.tcx().item_type(def_id);
313                     let concrete_ty = generic_ty.subst(self.tcx(), substs);
314                     self.fold_ty(concrete_ty)
315                 } else {
316                     ty
317                 }
318             }
319
320             ty::TyProjection(ref data) if !data.has_escaping_regions() => { // (*)
321
322                 // (*) This is kind of hacky -- we need to be able to
323                 // handle normalization within binders because
324                 // otherwise we wind up a need to normalize when doing
325                 // trait matching (since you can have a trait
326                 // obligation like `for<'a> T::B : Fn(&'a int)`), but
327                 // we can't normalize with bound regions in scope. So
328                 // far now we just ignore binders but only normalize
329                 // if all bound regions are gone (and then we still
330                 // have to renormalize whenever we instantiate a
331                 // binder). It would be better to normalize in a
332                 // binding-aware fashion.
333
334                 let Normalized { value: normalized_ty, obligations } =
335                     normalize_projection_type(self.selcx,
336                                               data.clone(),
337                                               self.cause.clone(),
338                                               self.depth);
339                 debug!("AssociatedTypeNormalizer: depth={} normalized {:?} to {:?} \
340                         with {} add'l obligations",
341                        self.depth, ty, normalized_ty, obligations.len());
342                 self.obligations.extend(obligations);
343                 normalized_ty
344             }
345
346             _ => {
347                 ty
348             }
349         }
350     }
351 }
352
353 #[derive(Clone)]
354 pub struct Normalized<'tcx,T> {
355     pub value: T,
356     pub obligations: Vec<PredicateObligation<'tcx>>,
357 }
358
359 pub type NormalizedTy<'tcx> = Normalized<'tcx, Ty<'tcx>>;
360
361 impl<'tcx,T> Normalized<'tcx,T> {
362     pub fn with<U>(self, value: U) -> Normalized<'tcx,U> {
363         Normalized { value: value, obligations: self.obligations }
364     }
365 }
366
367 /// The guts of `normalize`: normalize a specific projection like `<T
368 /// as Trait>::Item`. The result is always a type (and possibly
369 /// additional obligations). If ambiguity arises, which implies that
370 /// there are unresolved type variables in the projection, we will
371 /// substitute a fresh type variable `$X` and generate a new
372 /// obligation `<T as Trait>::Item == $X` for later.
373 pub fn normalize_projection_type<'a, 'b, 'gcx, 'tcx>(
374     selcx: &'a mut SelectionContext<'b, 'gcx, 'tcx>,
375     projection_ty: ty::ProjectionTy<'tcx>,
376     cause: ObligationCause<'tcx>,
377     depth: usize)
378     -> NormalizedTy<'tcx>
379 {
380     opt_normalize_projection_type(selcx, projection_ty.clone(), cause.clone(), depth)
381         .unwrap_or_else(move || {
382             // if we bottom out in ambiguity, create a type variable
383             // and a deferred predicate to resolve this when more type
384             // information is available.
385
386             let tcx = selcx.infcx().tcx;
387             let def_id = tcx.associated_items(projection_ty.trait_ref.def_id).find(|i|
388                 i.name == projection_ty.item_name && i.kind == ty::AssociatedKind::Type
389             ).map(|i| i.def_id).unwrap();
390             let ty_var = selcx.infcx().next_ty_var(
391                 TypeVariableOrigin::NormalizeProjectionType(tcx.def_span(def_id)));
392             let projection = ty::Binder(ty::ProjectionPredicate {
393                 projection_ty: projection_ty,
394                 ty: ty_var
395             });
396             let obligation = Obligation::with_depth(
397                 cause, depth + 1, projection.to_predicate());
398             Normalized {
399                 value: ty_var,
400                 obligations: vec![obligation]
401             }
402         })
403 }
404
405 /// The guts of `normalize`: normalize a specific projection like `<T
406 /// as Trait>::Item`. The result is always a type (and possibly
407 /// additional obligations). Returns `None` in the case of ambiguity,
408 /// which indicates that there are unbound type variables.
409 fn opt_normalize_projection_type<'a, 'b, 'gcx, 'tcx>(
410     selcx: &'a mut SelectionContext<'b, 'gcx, 'tcx>,
411     projection_ty: ty::ProjectionTy<'tcx>,
412     cause: ObligationCause<'tcx>,
413     depth: usize)
414     -> Option<NormalizedTy<'tcx>>
415 {
416     let infcx = selcx.infcx();
417
418     let projection_ty = infcx.resolve_type_vars_if_possible(&projection_ty);
419
420     debug!("opt_normalize_projection_type(\
421            projection_ty={:?}, \
422            depth={})",
423            projection_ty,
424            depth);
425
426     // FIXME(#20304) For now, I am caching here, which is good, but it
427     // means we don't capture the type variables that are created in
428     // the case of ambiguity. Which means we may create a large stream
429     // of such variables. OTOH, if we move the caching up a level, we
430     // would not benefit from caching when proving `T: Trait<U=Foo>`
431     // bounds. It might be the case that we want two distinct caches,
432     // or else another kind of cache entry.
433
434     match infcx.projection_cache.borrow_mut().try_start(projection_ty) {
435         Ok(()) => { }
436         Err(ProjectionCacheEntry::Ambiguous) => {
437             // If we found ambiguity the last time, that generally
438             // means we will continue to do so until some type in the
439             // key changes (and we know it hasn't, because we just
440             // fully resolved it). One exception though is closure
441             // types, which can transition from having a fixed kind to
442             // no kind with no visible change in the key.
443             //
444             // FIXME(#32286) refactor this so that closure type
445             // changes
446             debug!("opt_normalize_projection_type: \
447                     found cache entry: ambiguous");
448             if !projection_ty.has_closure_types() {
449                 return None;
450             }
451         }
452         Err(ProjectionCacheEntry::InProgress) => {
453             // If while normalized A::B, we are asked to normalize
454             // A::B, just return A::B itself. This is a conservative
455             // answer, in the sense that A::B *is* clearly equivalent
456             // to A::B, though there may be a better value we can
457             // find.
458
459             // Under lazy normalization, this can arise when
460             // bootstrapping.  That is, imagine an environment with a
461             // where-clause like `A::B == u32`. Now, if we are asked
462             // to normalize `A::B`, we will want to check the
463             // where-clauses in scope. So we will try to unify `A::B`
464             // with `A::B`, which can trigger a recursive
465             // normalization. In that case, I think we will want this code:
466             //
467             // ```
468             // let ty = selcx.tcx().mk_projection(projection_ty.trait_ref,
469             //                                    projection_ty.item_name);
470             // return Some(NormalizedTy { value: v, obligations: vec![] });
471             // ```
472
473             debug!("opt_normalize_projection_type: \
474                     found cache entry: in-progress");
475
476             // But for now, let's classify this as an overflow:
477             let recursion_limit = selcx.tcx().sess.recursion_limit.get();
478             let obligation = Obligation::with_depth(cause.clone(),
479                                                     recursion_limit,
480                                                     projection_ty);
481             selcx.infcx().report_overflow_error(&obligation, false);
482         }
483         Err(ProjectionCacheEntry::NormalizedTy(ty)) => {
484             // If we find the value in the cache, then the obligations
485             // have already been returned from the previous entry (and
486             // should therefore have been honored).
487             debug!("opt_normalize_projection_type: \
488                     found normalized ty `{:?}`",
489                    ty);
490             return Some(NormalizedTy { value: ty, obligations: vec![] });
491         }
492         Err(ProjectionCacheEntry::Error) => {
493             debug!("opt_normalize_projection_type: \
494                     found error");
495             return Some(normalize_to_error(selcx, projection_ty, cause, depth));
496         }
497     }
498
499     let obligation = Obligation::with_depth(cause.clone(), depth, projection_ty.clone());
500     match project_type(selcx, &obligation) {
501         Ok(ProjectedTy::Progress(Progress { ty: projected_ty,
502                                             mut obligations,
503                                             cacheable })) => {
504             // if projection succeeded, then what we get out of this
505             // is also non-normalized (consider: it was derived from
506             // an impl, where-clause etc) and hence we must
507             // re-normalize it
508
509             debug!("opt_normalize_projection_type: \
510                     projected_ty={:?} \
511                     depth={} \
512                     obligations={:?} \
513                     cacheable={:?}",
514                    projected_ty,
515                    depth,
516                    obligations,
517                    cacheable);
518
519             let result = if projected_ty.has_projection_types() {
520                 let mut normalizer = AssociatedTypeNormalizer::new(selcx, cause, depth+1);
521                 let normalized_ty = normalizer.fold(&projected_ty);
522
523                 debug!("opt_normalize_projection_type: \
524                         normalized_ty={:?} depth={}",
525                        normalized_ty,
526                        depth);
527
528                 obligations.extend(normalizer.obligations);
529                 Normalized {
530                     value: normalized_ty,
531                     obligations: obligations,
532                 }
533             } else {
534                 Normalized {
535                     value: projected_ty,
536                     obligations: obligations,
537                 }
538             };
539             infcx.projection_cache.borrow_mut()
540                                   .complete(projection_ty, &result, cacheable);
541             Some(result)
542         }
543         Ok(ProjectedTy::NoProgress(projected_ty)) => {
544             debug!("opt_normalize_projection_type: \
545                     projected_ty={:?} no progress",
546                    projected_ty);
547             let result = Normalized {
548                 value: projected_ty,
549                 obligations: vec![]
550             };
551             infcx.projection_cache.borrow_mut()
552                                   .complete(projection_ty, &result, true);
553             Some(result)
554         }
555         Err(ProjectionTyError::TooManyCandidates) => {
556             debug!("opt_normalize_projection_type: \
557                     too many candidates");
558             infcx.projection_cache.borrow_mut()
559                                   .ambiguous(projection_ty);
560             None
561         }
562         Err(ProjectionTyError::TraitSelectionError(_)) => {
563             debug!("opt_normalize_projection_type: ERROR");
564             // if we got an error processing the `T as Trait` part,
565             // just return `ty::err` but add the obligation `T :
566             // Trait`, which when processed will cause the error to be
567             // reported later
568
569             infcx.projection_cache.borrow_mut()
570                                   .error(projection_ty);
571             Some(normalize_to_error(selcx, projection_ty, cause, depth))
572         }
573     }
574 }
575
576 /// If we are projecting `<T as Trait>::Item`, but `T: Trait` does not
577 /// hold. In various error cases, we cannot generate a valid
578 /// normalized projection. Therefore, we create an inference variable
579 /// return an associated obligation that, when fulfilled, will lead to
580 /// an error.
581 ///
582 /// Note that we used to return `TyError` here, but that was quite
583 /// dubious -- the premise was that an error would *eventually* be
584 /// reported, when the obligation was processed. But in general once
585 /// you see a `TyError` you are supposed to be able to assume that an
586 /// error *has been* reported, so that you can take whatever heuristic
587 /// paths you want to take. To make things worse, it was possible for
588 /// cycles to arise, where you basically had a setup like `<MyType<$0>
589 /// as Trait>::Foo == $0`. Here, normalizing `<MyType<$0> as
590 /// Trait>::Foo> to `[type error]` would lead to an obligation of
591 /// `<MyType<[type error]> as Trait>::Foo`.  We are supposed to report
592 /// an error for this obligation, but we legitimately should not,
593 /// because it contains `[type error]`. Yuck! (See issue #29857 for
594 /// one case where this arose.)
595 fn normalize_to_error<'a, 'gcx, 'tcx>(selcx: &mut SelectionContext<'a, 'gcx, 'tcx>,
596                                       projection_ty: ty::ProjectionTy<'tcx>,
597                                       cause: ObligationCause<'tcx>,
598                                       depth: usize)
599                                       -> NormalizedTy<'tcx>
600 {
601     let trait_ref = projection_ty.trait_ref.to_poly_trait_ref();
602     let trait_obligation = Obligation { cause: cause,
603                                         recursion_depth: depth,
604                                         predicate: trait_ref.to_predicate() };
605     let tcx = selcx.infcx().tcx;
606     let def_id = tcx.associated_items(projection_ty.trait_ref.def_id).find(|i|
607         i.name == projection_ty.item_name && i.kind == ty::AssociatedKind::Type
608     ).map(|i| i.def_id).unwrap();
609     let new_value = selcx.infcx().next_ty_var(
610         TypeVariableOrigin::NormalizeProjectionType(tcx.def_span(def_id)));
611     Normalized {
612         value: new_value,
613         obligations: vec![trait_obligation]
614     }
615 }
616
617 enum ProjectedTy<'tcx> {
618     Progress(Progress<'tcx>),
619     NoProgress(Ty<'tcx>),
620 }
621
622 struct Progress<'tcx> {
623     ty: Ty<'tcx>,
624     obligations: Vec<PredicateObligation<'tcx>>,
625     cacheable: bool,
626 }
627
628 impl<'tcx> Progress<'tcx> {
629     fn error<'a,'gcx>(tcx: TyCtxt<'a,'gcx,'tcx>) -> Self {
630         Progress {
631             ty: tcx.types.err,
632             obligations: vec![],
633             cacheable: true
634         }
635     }
636
637     fn with_addl_obligations(mut self,
638                              mut obligations: Vec<PredicateObligation<'tcx>>)
639                              -> Self {
640         debug!("with_addl_obligations: self.obligations.len={} obligations.len={}",
641                self.obligations.len(), obligations.len());
642
643         debug!("with_addl_obligations: self.obligations={:?} obligations={:?}",
644                self.obligations, obligations);
645
646         self.obligations.append(&mut obligations);
647         self
648     }
649 }
650
651 /// Compute the result of a projection type (if we can).
652 ///
653 /// IMPORTANT:
654 /// - `obligation` must be fully normalized
655 fn project_type<'cx, 'gcx, 'tcx>(
656     selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
657     obligation: &ProjectionTyObligation<'tcx>)
658     -> Result<ProjectedTy<'tcx>, ProjectionTyError<'tcx>>
659 {
660     debug!("project(obligation={:?})",
661            obligation);
662
663     let recursion_limit = selcx.tcx().sess.recursion_limit.get();
664     if obligation.recursion_depth >= recursion_limit {
665         debug!("project: overflow!");
666         selcx.infcx().report_overflow_error(&obligation, true);
667     }
668
669     let obligation_trait_ref = &obligation.predicate.trait_ref;
670
671     debug!("project: obligation_trait_ref={:?}", obligation_trait_ref);
672
673     if obligation_trait_ref.references_error() {
674         return Ok(ProjectedTy::Progress(Progress::error(selcx.tcx())));
675     }
676
677     let mut candidates = ProjectionTyCandidateSet {
678         vec: Vec::new(),
679         ambiguous: false,
680     };
681
682     assemble_candidates_from_param_env(selcx,
683                                        obligation,
684                                        &obligation_trait_ref,
685                                        &mut candidates);
686
687     assemble_candidates_from_trait_def(selcx,
688                                        obligation,
689                                        &obligation_trait_ref,
690                                        &mut candidates);
691
692     if let Err(e) = assemble_candidates_from_impls(selcx,
693                                                    obligation,
694                                                    &obligation_trait_ref,
695                                                    &mut candidates) {
696         return Err(ProjectionTyError::TraitSelectionError(e));
697     }
698
699     debug!("{} candidates, ambiguous={}",
700            candidates.vec.len(),
701            candidates.ambiguous);
702
703     // Inherent ambiguity that prevents us from even enumerating the
704     // candidates.
705     if candidates.ambiguous {
706         return Err(ProjectionTyError::TooManyCandidates);
707     }
708
709     // Drop duplicates.
710     //
711     // Note: `candidates.vec` seems to be on the critical path of the
712     // compiler. Replacing it with an hash set was also tried, which would
713     // render the following dedup unnecessary. It led to cleaner code but
714     // prolonged compiling time of `librustc` from 5m30s to 6m in one test, or
715     // ~9% performance lost.
716     if candidates.vec.len() > 1 {
717         let mut i = 0;
718         while i < candidates.vec.len() {
719             let has_dup = (0..i).any(|j| candidates.vec[i] == candidates.vec[j]);
720             if has_dup {
721                 candidates.vec.swap_remove(i);
722             } else {
723                 i += 1;
724             }
725         }
726     }
727
728     // Prefer where-clauses. As in select, if there are multiple
729     // candidates, we prefer where-clause candidates over impls.  This
730     // may seem a bit surprising, since impls are the source of
731     // "truth" in some sense, but in fact some of the impls that SEEM
732     // applicable are not, because of nested obligations. Where
733     // clauses are the safer choice. See the comment on
734     // `select::SelectionCandidate` and #21974 for more details.
735     if candidates.vec.len() > 1 {
736         debug!("retaining param-env candidates only from {:?}", candidates.vec);
737         candidates.vec.retain(|c| match *c {
738             ProjectionTyCandidate::ParamEnv(..) => true,
739             ProjectionTyCandidate::TraitDef(..) |
740             ProjectionTyCandidate::Select => false,
741         });
742         debug!("resulting candidate set: {:?}", candidates.vec);
743         if candidates.vec.len() != 1 {
744             return Err(ProjectionTyError::TooManyCandidates);
745         }
746     }
747
748     assert!(candidates.vec.len() <= 1);
749
750     match candidates.vec.pop() {
751         Some(candidate) => {
752             Ok(ProjectedTy::Progress(
753                 confirm_candidate(selcx,
754                                   obligation,
755                                   &obligation_trait_ref,
756                                   candidate)))
757         }
758         None => {
759             Ok(ProjectedTy::NoProgress(
760                 selcx.tcx().mk_projection(
761                     obligation.predicate.trait_ref.clone(),
762                     obligation.predicate.item_name)))
763         }
764     }
765 }
766
767 /// The first thing we have to do is scan through the parameter
768 /// environment to see whether there are any projection predicates
769 /// there that can answer this question.
770 fn assemble_candidates_from_param_env<'cx, 'gcx, 'tcx>(
771     selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
772     obligation: &ProjectionTyObligation<'tcx>,
773     obligation_trait_ref: &ty::TraitRef<'tcx>,
774     candidate_set: &mut ProjectionTyCandidateSet<'tcx>)
775 {
776     debug!("assemble_candidates_from_param_env(..)");
777     let env_predicates = selcx.param_env().caller_bounds.iter().cloned();
778     assemble_candidates_from_predicates(selcx,
779                                         obligation,
780                                         obligation_trait_ref,
781                                         candidate_set,
782                                         ProjectionTyCandidate::ParamEnv,
783                                         env_predicates);
784 }
785
786 /// In the case of a nested projection like <<A as Foo>::FooT as Bar>::BarT, we may find
787 /// that the definition of `Foo` has some clues:
788 ///
789 /// ```
790 /// trait Foo {
791 ///     type FooT : Bar<BarT=i32>
792 /// }
793 /// ```
794 ///
795 /// Here, for example, we could conclude that the result is `i32`.
796 fn assemble_candidates_from_trait_def<'cx, 'gcx, 'tcx>(
797     selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
798     obligation: &ProjectionTyObligation<'tcx>,
799     obligation_trait_ref: &ty::TraitRef<'tcx>,
800     candidate_set: &mut ProjectionTyCandidateSet<'tcx>)
801 {
802     debug!("assemble_candidates_from_trait_def(..)");
803
804     // Check whether the self-type is itself a projection.
805     let (def_id, substs) = match obligation_trait_ref.self_ty().sty {
806         ty::TyProjection(ref data) => {
807             (data.trait_ref.def_id, data.trait_ref.substs)
808         }
809         ty::TyAnon(def_id, substs) => (def_id, substs),
810         ty::TyInfer(ty::TyVar(_)) => {
811             // If the self-type is an inference variable, then it MAY wind up
812             // being a projected type, so induce an ambiguity.
813             candidate_set.ambiguous = true;
814             return;
815         }
816         _ => { return; }
817     };
818
819     // If so, extract what we know from the trait and try to come up with a good answer.
820     let trait_predicates = selcx.tcx().item_predicates(def_id);
821     let bounds = trait_predicates.instantiate(selcx.tcx(), substs);
822     let bounds = elaborate_predicates(selcx.tcx(), bounds.predicates);
823     assemble_candidates_from_predicates(selcx,
824                                         obligation,
825                                         obligation_trait_ref,
826                                         candidate_set,
827                                         ProjectionTyCandidate::TraitDef,
828                                         bounds)
829 }
830
831 fn assemble_candidates_from_predicates<'cx, 'gcx, 'tcx, I>(
832     selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
833     obligation: &ProjectionTyObligation<'tcx>,
834     obligation_trait_ref: &ty::TraitRef<'tcx>,
835     candidate_set: &mut ProjectionTyCandidateSet<'tcx>,
836     ctor: fn(ty::PolyProjectionPredicate<'tcx>) -> ProjectionTyCandidate<'tcx>,
837     env_predicates: I)
838     where I: Iterator<Item=ty::Predicate<'tcx>>
839 {
840     debug!("assemble_candidates_from_predicates(obligation={:?})",
841            obligation);
842     let infcx = selcx.infcx();
843     for predicate in env_predicates {
844         debug!("assemble_candidates_from_predicates: predicate={:?}",
845                predicate);
846         match predicate {
847             ty::Predicate::Projection(ref data) => {
848                 let same_name = data.item_name() == obligation.predicate.item_name;
849
850                 let is_match = same_name && infcx.probe(|_| {
851                     let data_poly_trait_ref =
852                         data.to_poly_trait_ref();
853                     let obligation_poly_trait_ref =
854                         obligation_trait_ref.to_poly_trait_ref();
855                     infcx.sub_poly_trait_refs(false,
856                                               obligation.cause.clone(),
857                                               data_poly_trait_ref,
858                                               obligation_poly_trait_ref)
859                         .map(|InferOk { obligations: _, value: () }| {
860                             // FIXME(#32730) -- do we need to take obligations
861                             // into account in any way? At the moment, no.
862                         })
863                         .is_ok()
864                 });
865
866                 debug!("assemble_candidates_from_predicates: candidate={:?} \
867                                                              is_match={} same_name={}",
868                        data, is_match, same_name);
869
870                 if is_match {
871                     candidate_set.vec.push(ctor(data.clone()));
872                 }
873             }
874             _ => { }
875         }
876     }
877 }
878
879 fn assemble_candidates_from_impls<'cx, 'gcx, 'tcx>(
880     selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
881     obligation: &ProjectionTyObligation<'tcx>,
882     obligation_trait_ref: &ty::TraitRef<'tcx>,
883     candidate_set: &mut ProjectionTyCandidateSet<'tcx>)
884     -> Result<(), SelectionError<'tcx>>
885 {
886     // If we are resolving `<T as TraitRef<...>>::Item == Type`,
887     // start out by selecting the predicate `T as TraitRef<...>`:
888     let poly_trait_ref = obligation_trait_ref.to_poly_trait_ref();
889     let trait_obligation = obligation.with(poly_trait_ref.to_poly_trait_predicate());
890     selcx.infcx().probe(|_| {
891         let vtable = match selcx.select(&trait_obligation) {
892             Ok(Some(vtable)) => vtable,
893             Ok(None) => {
894                 candidate_set.ambiguous = true;
895                 return Ok(());
896             }
897             Err(e) => {
898                 debug!("assemble_candidates_from_impls: selection error {:?}",
899                        e);
900                 return Err(e);
901             }
902         };
903
904         match vtable {
905             super::VtableClosure(_) |
906             super::VtableFnPointer(_) |
907             super::VtableObject(_) => {
908                 debug!("assemble_candidates_from_impls: vtable={:?}",
909                        vtable);
910
911                 candidate_set.vec.push(ProjectionTyCandidate::Select);
912             }
913             super::VtableImpl(ref impl_data) => {
914                 // We have to be careful when projecting out of an
915                 // impl because of specialization. If we are not in
916                 // trans (i.e., projection mode is not "any"), and the
917                 // impl's type is declared as default, then we disable
918                 // projection (even if the trait ref is fully
919                 // monomorphic). In the case where trait ref is not
920                 // fully monomorphic (i.e., includes type parameters),
921                 // this is because those type parameters may
922                 // ultimately be bound to types from other crates that
923                 // may have specialized impls we can't see. In the
924                 // case where the trait ref IS fully monomorphic, this
925                 // is a policy decision that we made in the RFC in
926                 // order to preserve flexibility for the crate that
927                 // defined the specializable impl to specialize later
928                 // for existing types.
929                 //
930                 // In either case, we handle this by not adding a
931                 // candidate for an impl if it contains a `default`
932                 // type.
933                 let opt_node_item = assoc_ty_def(selcx,
934                                                  impl_data.impl_def_id,
935                                                  obligation.predicate.item_name);
936                 let new_candidate = if let Some(node_item) = opt_node_item {
937                     let is_default = if node_item.node.is_from_trait() {
938                         // If true, the impl inherited a `type Foo = Bar`
939                         // given in the trait, which is implicitly default.
940                         // Otherwise, the impl did not specify `type` and
941                         // neither did the trait:
942                         //
943                         // ```rust
944                         // trait Foo { type T; }
945                         // impl Foo for Bar { }
946                         // ```
947                         //
948                         // This is an error, but it will be
949                         // reported in `check_impl_items_against_trait`.
950                         // We accept it here but will flag it as
951                         // an error when we confirm the candidate
952                         // (which will ultimately lead to `normalize_to_error`
953                         // being invoked).
954                         node_item.item.defaultness.has_value()
955                     } else {
956                         node_item.item.defaultness.is_default()
957                     };
958
959                     // Only reveal a specializable default if we're past type-checking
960                     // and the obligations is monomorphic, otherwise passes such as
961                     // transmute checking and polymorphic MIR optimizations could
962                     // get a result which isn't correct for all monomorphizations.
963                     if !is_default {
964                         Some(ProjectionTyCandidate::Select)
965                     } else if selcx.projection_mode() == Reveal::All {
966                         assert!(!poly_trait_ref.needs_infer());
967                         if !poly_trait_ref.needs_subst() {
968                             Some(ProjectionTyCandidate::Select)
969                         } else {
970                             None
971                         }
972                     } else {
973                         None
974                     }
975                 } else {
976                     // This is saying that neither the trait nor
977                     // the impl contain a definition for this
978                     // associated type.  Normally this situation
979                     // could only arise through a compiler bug --
980                     // if the user wrote a bad item name, it
981                     // should have failed in astconv. **However**,
982                     // at coherence-checking time, we only look at
983                     // the topmost impl (we don't even consider
984                     // the trait itself) for the definition -- and
985                     // so in that case it may be that the trait
986                     // *DOES* have a declaration, but we don't see
987                     // it, and we end up in this branch.
988                     //
989                     // This is kind of tricky to handle actually.
990                     // For now, we just unconditionally ICE,
991                     // because otherwise, examples like the
992                     // following will succeed:
993                     //
994                     // ```
995                     // trait Assoc {
996                     //     type Output;
997                     // }
998                     //
999                     // impl<T> Assoc for T {
1000                     //     default type Output = bool;
1001                     // }
1002                     //
1003                     // impl Assoc for u8 {}
1004                     // impl Assoc for u16 {}
1005                     //
1006                     // trait Foo {}
1007                     // impl Foo for <u8 as Assoc>::Output {}
1008                     // impl Foo for <u16 as Assoc>::Output {}
1009                     //     return None;
1010                     // }
1011                     // ```
1012                     //
1013                     // The essential problem here is that the
1014                     // projection fails, leaving two unnormalized
1015                     // types, which appear not to unify -- so the
1016                     // overlap check succeeds, when it should
1017                     // fail.
1018                     span_bug!(obligation.cause.span,
1019                               "Tried to project an inherited associated type during \
1020                                coherence checking, which is currently not supported.");
1021                 };
1022                 candidate_set.vec.extend(new_candidate);
1023             }
1024             super::VtableParam(..) => {
1025                 // This case tell us nothing about the value of an
1026                 // associated type. Consider:
1027                 //
1028                 // ```
1029                 // trait SomeTrait { type Foo; }
1030                 // fn foo<T:SomeTrait>(...) { }
1031                 // ```
1032                 //
1033                 // If the user writes `<T as SomeTrait>::Foo`, then the `T
1034                 // : SomeTrait` binding does not help us decide what the
1035                 // type `Foo` is (at least, not more specifically than
1036                 // what we already knew).
1037                 //
1038                 // But wait, you say! What about an example like this:
1039                 //
1040                 // ```
1041                 // fn bar<T:SomeTrait<Foo=usize>>(...) { ... }
1042                 // ```
1043                 //
1044                 // Doesn't the `T : Sometrait<Foo=usize>` predicate help
1045                 // resolve `T::Foo`? And of course it does, but in fact
1046                 // that single predicate is desugared into two predicates
1047                 // in the compiler: a trait predicate (`T : SomeTrait`) and a
1048                 // projection. And the projection where clause is handled
1049                 // in `assemble_candidates_from_param_env`.
1050             }
1051             super::VtableDefaultImpl(..) |
1052             super::VtableBuiltin(..) => {
1053                 // These traits have no associated types.
1054                 span_bug!(
1055                     obligation.cause.span,
1056                     "Cannot project an associated type from `{:?}`",
1057                     vtable);
1058             }
1059         }
1060
1061         Ok(())
1062     })
1063 }
1064
1065 fn confirm_candidate<'cx, 'gcx, 'tcx>(
1066     selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
1067     obligation: &ProjectionTyObligation<'tcx>,
1068     obligation_trait_ref: &ty::TraitRef<'tcx>,
1069     candidate: ProjectionTyCandidate<'tcx>)
1070     -> Progress<'tcx>
1071 {
1072     debug!("confirm_candidate(candidate={:?}, obligation={:?})",
1073            candidate,
1074            obligation);
1075
1076     match candidate {
1077         ProjectionTyCandidate::ParamEnv(poly_projection) |
1078         ProjectionTyCandidate::TraitDef(poly_projection) => {
1079             confirm_param_env_candidate(selcx, obligation, poly_projection)
1080         }
1081
1082         ProjectionTyCandidate::Select => {
1083             confirm_select_candidate(selcx, obligation, obligation_trait_ref)
1084         }
1085     }
1086 }
1087
1088 fn confirm_select_candidate<'cx, 'gcx, 'tcx>(
1089     selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
1090     obligation: &ProjectionTyObligation<'tcx>,
1091     obligation_trait_ref: &ty::TraitRef<'tcx>)
1092     -> Progress<'tcx>
1093 {
1094     let poly_trait_ref = obligation_trait_ref.to_poly_trait_ref();
1095     let trait_obligation = obligation.with(poly_trait_ref.to_poly_trait_predicate());
1096     let vtable = match selcx.select(&trait_obligation) {
1097         Ok(Some(vtable)) => vtable,
1098         _ => {
1099             span_bug!(
1100                 obligation.cause.span,
1101                 "Failed to select `{:?}`",
1102                 trait_obligation);
1103         }
1104     };
1105
1106     match vtable {
1107         super::VtableImpl(data) =>
1108             confirm_impl_candidate(selcx, obligation, data),
1109         super::VtableClosure(data) =>
1110             confirm_closure_candidate(selcx, obligation, data),
1111         super::VtableFnPointer(data) =>
1112             confirm_fn_pointer_candidate(selcx, obligation, data),
1113         super::VtableObject(_) =>
1114             confirm_object_candidate(selcx, obligation, obligation_trait_ref),
1115         super::VtableDefaultImpl(..) |
1116         super::VtableParam(..) |
1117         super::VtableBuiltin(..) =>
1118             // we don't create Select candidates with this kind of resolution
1119             span_bug!(
1120                 obligation.cause.span,
1121                 "Cannot project an associated type from `{:?}`",
1122                 vtable),
1123     }
1124 }
1125
1126 fn confirm_object_candidate<'cx, 'gcx, 'tcx>(
1127     selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
1128     obligation:  &ProjectionTyObligation<'tcx>,
1129     obligation_trait_ref: &ty::TraitRef<'tcx>)
1130     -> Progress<'tcx>
1131 {
1132     let self_ty = obligation_trait_ref.self_ty();
1133     let object_ty = selcx.infcx().shallow_resolve(self_ty);
1134     debug!("confirm_object_candidate(object_ty={:?})",
1135            object_ty);
1136     let data = match object_ty.sty {
1137         ty::TyDynamic(ref data, ..) => data,
1138         _ => {
1139             span_bug!(
1140                 obligation.cause.span,
1141                 "confirm_object_candidate called with non-object: {:?}",
1142                 object_ty)
1143         }
1144     };
1145     let env_predicates = data.projection_bounds().map(|p| {
1146         p.with_self_ty(selcx.tcx(), object_ty).to_predicate()
1147     }).collect();
1148     let env_predicate = {
1149         let env_predicates = elaborate_predicates(selcx.tcx(), env_predicates);
1150
1151         // select only those projections that are actually projecting an
1152         // item with the correct name
1153         let env_predicates = env_predicates.filter_map(|p| match p {
1154             ty::Predicate::Projection(data) =>
1155                 if data.item_name() == obligation.predicate.item_name {
1156                     Some(data)
1157                 } else {
1158                     None
1159                 },
1160             _ => None
1161         });
1162
1163         // select those with a relevant trait-ref
1164         let mut env_predicates = env_predicates.filter(|data| {
1165             let data_poly_trait_ref = data.to_poly_trait_ref();
1166             let obligation_poly_trait_ref = obligation_trait_ref.to_poly_trait_ref();
1167             selcx.infcx().probe(|_| {
1168                 selcx.infcx().sub_poly_trait_refs(false,
1169                                                   obligation.cause.clone(),
1170                                                   data_poly_trait_ref,
1171                                                   obligation_poly_trait_ref).is_ok()
1172             })
1173         });
1174
1175         // select the first matching one; there really ought to be one or
1176         // else the object type is not WF, since an object type should
1177         // include all of its projections explicitly
1178         match env_predicates.next() {
1179             Some(env_predicate) => env_predicate,
1180             None => {
1181                 debug!("confirm_object_candidate: no env-predicate \
1182                         found in object type `{:?}`; ill-formed",
1183                        object_ty);
1184                 return Progress::error(selcx.tcx());
1185             }
1186         }
1187     };
1188
1189     confirm_param_env_candidate(selcx, obligation, env_predicate)
1190 }
1191
1192 fn confirm_fn_pointer_candidate<'cx, 'gcx, 'tcx>(
1193     selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
1194     obligation: &ProjectionTyObligation<'tcx>,
1195     fn_pointer_vtable: VtableFnPointerData<'tcx, PredicateObligation<'tcx>>)
1196     -> Progress<'tcx>
1197 {
1198     let fn_type = selcx.infcx().shallow_resolve(fn_pointer_vtable.fn_ty);
1199     let sig = fn_type.fn_sig();
1200     confirm_callable_candidate(selcx, obligation, sig, util::TupleArgumentsFlag::Yes)
1201         .with_addl_obligations(fn_pointer_vtable.nested)
1202 }
1203
1204 fn confirm_closure_candidate<'cx, 'gcx, 'tcx>(
1205     selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
1206     obligation: &ProjectionTyObligation<'tcx>,
1207     vtable: VtableClosureData<'tcx, PredicateObligation<'tcx>>)
1208     -> Progress<'tcx>
1209 {
1210     let closure_typer = selcx.closure_typer();
1211     let closure_type = closure_typer.closure_type(vtable.closure_def_id, vtable.substs);
1212     let Normalized {
1213         value: closure_type,
1214         obligations
1215     } = normalize_with_depth(selcx,
1216                              obligation.cause.clone(),
1217                              obligation.recursion_depth+1,
1218                              &closure_type);
1219
1220     debug!("confirm_closure_candidate: obligation={:?},closure_type={:?},obligations={:?}",
1221            obligation,
1222            closure_type,
1223            obligations);
1224
1225     confirm_callable_candidate(selcx,
1226                                obligation,
1227                                &closure_type.sig,
1228                                util::TupleArgumentsFlag::No)
1229         .with_addl_obligations(vtable.nested)
1230         .with_addl_obligations(obligations)
1231 }
1232
1233 fn confirm_callable_candidate<'cx, 'gcx, 'tcx>(
1234     selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
1235     obligation: &ProjectionTyObligation<'tcx>,
1236     fn_sig: &ty::PolyFnSig<'tcx>,
1237     flag: util::TupleArgumentsFlag)
1238     -> Progress<'tcx>
1239 {
1240     let tcx = selcx.tcx();
1241
1242     debug!("confirm_callable_candidate({:?},{:?})",
1243            obligation,
1244            fn_sig);
1245
1246     // the `Output` associated type is declared on `FnOnce`
1247     let fn_once_def_id = tcx.lang_items.fn_once_trait().unwrap();
1248
1249     // Note: we unwrap the binder here but re-create it below (1)
1250     let ty::Binder((trait_ref, ret_type)) =
1251         tcx.closure_trait_ref_and_return_type(fn_once_def_id,
1252                                               obligation.predicate.trait_ref.self_ty(),
1253                                               fn_sig,
1254                                               flag);
1255
1256     let predicate = ty::Binder(ty::ProjectionPredicate { // (1) recreate binder here
1257         projection_ty: ty::ProjectionTy {
1258             trait_ref: trait_ref,
1259             item_name: Symbol::intern(FN_OUTPUT_NAME),
1260         },
1261         ty: ret_type
1262     });
1263
1264     confirm_param_env_candidate(selcx, obligation, predicate)
1265 }
1266
1267 fn confirm_param_env_candidate<'cx, 'gcx, 'tcx>(
1268     selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
1269     obligation: &ProjectionTyObligation<'tcx>,
1270     poly_projection: ty::PolyProjectionPredicate<'tcx>)
1271     -> Progress<'tcx>
1272 {
1273     let infcx = selcx.infcx();
1274     let cause = obligation.cause.clone();
1275     let trait_ref = obligation.predicate.trait_ref;
1276     match infcx.match_poly_projection_predicate(cause, poly_projection, trait_ref) {
1277         Ok(InferOk { value: ty_match, obligations }) => {
1278             Progress {
1279                 ty: ty_match.value,
1280                 obligations: obligations,
1281                 cacheable: ty_match.unconstrained_regions.is_empty(),
1282             }
1283         }
1284         Err(e) => {
1285             span_bug!(
1286                 obligation.cause.span,
1287                 "Failed to unify obligation `{:?}` \
1288                  with poly_projection `{:?}`: {:?}",
1289                 obligation,
1290                 poly_projection,
1291                 e);
1292         }
1293     }
1294 }
1295
1296 fn confirm_impl_candidate<'cx, 'gcx, 'tcx>(
1297     selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
1298     obligation: &ProjectionTyObligation<'tcx>,
1299     impl_vtable: VtableImplData<'tcx, PredicateObligation<'tcx>>)
1300     -> Progress<'tcx>
1301 {
1302     let VtableImplData { substs, nested, impl_def_id } = impl_vtable;
1303
1304     let tcx = selcx.tcx();
1305     let trait_ref = obligation.predicate.trait_ref;
1306     let assoc_ty = assoc_ty_def(selcx, impl_def_id, obligation.predicate.item_name);
1307
1308     match assoc_ty {
1309         Some(node_item) => {
1310             let ty = if !node_item.item.defaultness.has_value() {
1311                 // This means that the impl is missing a definition for the
1312                 // associated type. This error will be reported by the type
1313                 // checker method `check_impl_items_against_trait`, so here we
1314                 // just return TyError.
1315                 debug!("confirm_impl_candidate: no associated type {:?} for {:?}",
1316                        node_item.item.name,
1317                        obligation.predicate.trait_ref);
1318                 tcx.types.err
1319             } else {
1320                 tcx.item_type(node_item.item.def_id)
1321             };
1322             let substs = translate_substs(selcx.infcx(), impl_def_id, substs, node_item.node);
1323             Progress {
1324                 ty: ty.subst(tcx, substs),
1325                 obligations: nested,
1326                 cacheable: true
1327             }
1328         }
1329         None => {
1330             span_bug!(obligation.cause.span,
1331                       "No associated type for {:?}",
1332                       trait_ref);
1333         }
1334     }
1335 }
1336
1337 /// Locate the definition of an associated type in the specialization hierarchy,
1338 /// starting from the given impl.
1339 ///
1340 /// Based on the "projection mode", this lookup may in fact only examine the
1341 /// topmost impl. See the comments for `Reveal` for more details.
1342 fn assoc_ty_def<'cx, 'gcx, 'tcx>(
1343     selcx: &SelectionContext<'cx, 'gcx, 'tcx>,
1344     impl_def_id: DefId,
1345     assoc_ty_name: ast::Name)
1346     -> Option<specialization_graph::NodeItem<ty::AssociatedItem>>
1347 {
1348     let trait_def_id = selcx.tcx().impl_trait_ref(impl_def_id).unwrap().def_id;
1349
1350     if selcx.projection_mode() == Reveal::ExactMatch {
1351         let impl_node = specialization_graph::Node::Impl(impl_def_id);
1352         for item in impl_node.items(selcx.tcx()) {
1353             if item.kind == ty::AssociatedKind::Type && item.name == assoc_ty_name {
1354                 return Some(specialization_graph::NodeItem {
1355                     node: specialization_graph::Node::Impl(impl_def_id),
1356                     item: item,
1357                 });
1358             }
1359         }
1360         None
1361     } else {
1362         selcx.tcx().lookup_trait_def(trait_def_id)
1363             .ancestors(impl_def_id)
1364             .defs(selcx.tcx(), assoc_ty_name, ty::AssociatedKind::Type)
1365             .next()
1366     }
1367 }
1368
1369 // # Cache
1370
1371 pub struct ProjectionCache<'tcx> {
1372     map: SnapshotMap<ty::ProjectionTy<'tcx>, ProjectionCacheEntry<'tcx>>,
1373 }
1374
1375 #[derive(Clone, Debug)]
1376 enum ProjectionCacheEntry<'tcx> {
1377     InProgress,
1378     Ambiguous,
1379     Error,
1380     NormalizedTy(Ty<'tcx>),
1381 }
1382
1383 // NB: intentionally not Clone
1384 pub struct ProjectionCacheSnapshot {
1385     snapshot: Snapshot
1386 }
1387
1388 impl<'tcx> ProjectionCache<'tcx> {
1389     pub fn new() -> Self {
1390         ProjectionCache {
1391             map: SnapshotMap::new()
1392         }
1393     }
1394
1395     pub fn snapshot(&mut self) -> ProjectionCacheSnapshot {
1396         ProjectionCacheSnapshot { snapshot: self.map.snapshot() }
1397     }
1398
1399     pub fn rollback_to(&mut self, snapshot: ProjectionCacheSnapshot) {
1400         self.map.rollback_to(snapshot.snapshot);
1401     }
1402
1403     pub fn rollback_skolemized(&mut self, snapshot: &ProjectionCacheSnapshot) {
1404         self.map.partial_rollback(&snapshot.snapshot, &|k| k.has_re_skol());
1405     }
1406
1407     pub fn commit(&mut self, snapshot: ProjectionCacheSnapshot) {
1408         self.map.commit(snapshot.snapshot);
1409     }
1410
1411     /// Try to start normalize `key`; returns an error if
1412     /// normalization already occured (this error corresponds to a
1413     /// cache hit, so it's actually a good thing).
1414     fn try_start(&mut self, key: ty::ProjectionTy<'tcx>)
1415                  -> Result<(), ProjectionCacheEntry<'tcx>> {
1416         if let Some(entry) = self.map.get(&key) {
1417             return Err(entry.clone());
1418         }
1419
1420         self.map.insert(key, ProjectionCacheEntry::InProgress);
1421         Ok(())
1422     }
1423
1424     /// Indicates that `key` was normalized to `value`. If `cacheable` is false,
1425     /// then this result is sadly not cacheable.
1426     fn complete(&mut self,
1427                 key: ty::ProjectionTy<'tcx>,
1428                 value: &NormalizedTy<'tcx>,
1429                 cacheable: bool) {
1430         let fresh_key = if cacheable {
1431             debug!("ProjectionCacheEntry::complete: adding cache entry: key={:?}, value={:?}",
1432                    key, value);
1433             self.map.insert(key, ProjectionCacheEntry::NormalizedTy(value.value))
1434         } else {
1435             debug!("ProjectionCacheEntry::complete: cannot cache: key={:?}, value={:?}",
1436                    key, value);
1437             !self.map.remove(key)
1438         };
1439
1440         assert!(!fresh_key, "never started projecting `{:?}`", key);
1441     }
1442
1443     /// Indicates that trying to normalize `key` resulted in
1444     /// ambiguity. No point in trying it again then until we gain more
1445     /// type information (in which case, the "fully resolved" key will
1446     /// be different).
1447     fn ambiguous(&mut self, key: ty::ProjectionTy<'tcx>) {
1448         let fresh = self.map.insert(key, ProjectionCacheEntry::Ambiguous);
1449         assert!(!fresh, "never started projecting `{:?}`", key);
1450     }
1451
1452     /// Indicates that trying to normalize `key` resulted in
1453     /// error.
1454     fn error(&mut self, key: ty::ProjectionTy<'tcx>) {
1455         let fresh = self.map.insert(key, ProjectionCacheEntry::Error);
1456         assert!(!fresh, "never started projecting `{:?}`", key);
1457     }
1458 }