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.
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.
11 //! Code for projecting associated types out of trait references.
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;
26 use hir::def_id::DefId;
28 use infer::type_variable::TypeVariableOrigin;
29 use rustc_data_structures::snapshot_map::{Snapshot, SnapshotMap};
31 use syntax::symbol::Symbol;
33 use ty::{self, ToPredicate, ToPolyTraitRef, Ty, TyCtxt};
34 use ty::fold::{TypeFoldable, TypeFolder};
35 use util::common::FN_OUTPUT_NAME;
37 /// Depending on the stage of compilation, we want projection to be
38 /// more or less conservative.
39 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
41 /// At type-checking time, we refuse to project any associated
42 /// type that is marked `default`. Non-`default` ("final") types
43 /// are always projected. This is necessary in general for
44 /// soundness of specialization. However, we *could* allow
45 /// projections in fully-monomorphic cases. We choose not to,
46 /// because we prefer for `default type` to force the type
47 /// definition to be treated abstractly by any consumers of the
48 /// impl. Concretely, that means that the following example will
56 /// impl<T> Assoc for T {
57 /// default type Output = bool;
61 /// let <() as Assoc>::Output = true;
65 /// At trans time, all monomorphic projections will succeed.
66 /// Also, `impl Trait` is normalized to the concrete type,
67 /// which has to be already collected by type-checking.
69 /// NOTE: As `impl Trait`'s concrete type should *never*
70 /// be observable directly by the user, `Reveal::All`
71 /// should not be used by checks which may expose
72 /// type equality or type contents to the user.
73 /// There are some exceptions, e.g. around OIBITS and
74 /// transmute-checking, which expose some details, but
75 /// not the whole concrete type of the `impl Trait`.
79 pub type PolyProjectionObligation<'tcx> =
80 Obligation<'tcx, ty::PolyProjectionPredicate<'tcx>>;
82 pub type ProjectionObligation<'tcx> =
83 Obligation<'tcx, ty::ProjectionPredicate<'tcx>>;
85 pub type ProjectionTyObligation<'tcx> =
86 Obligation<'tcx, ty::ProjectionTy<'tcx>>;
88 /// When attempting to resolve `<T as TraitRef>::Name` ...
90 pub enum ProjectionTyError<'tcx> {
91 /// ...we found multiple sources of information and couldn't resolve the ambiguity.
94 /// ...an error occurred matching `T : TraitRef`
95 TraitSelectionError(SelectionError<'tcx>),
99 pub struct MismatchedProjectionTypes<'tcx> {
100 pub err: ty::error::TypeError<'tcx>
103 #[derive(PartialEq, Eq, Debug)]
104 enum ProjectionTyCandidate<'tcx> {
105 // from a where-clause in the env or object type
106 ParamEnv(ty::PolyProjectionPredicate<'tcx>),
108 // from the definition of `Trait` when you have something like <<A as Trait>::B as Trait2>::C
109 TraitDef(ty::PolyProjectionPredicate<'tcx>),
111 // from a "impl" (or a "pseudo-impl" returned by select)
115 struct ProjectionTyCandidateSet<'tcx> {
116 vec: Vec<ProjectionTyCandidate<'tcx>>,
120 /// Evaluates constraints of the form:
122 /// for<...> <T as Trait>::U == V
124 /// If successful, this may result in additional obligations.
125 pub fn poly_project_and_unify_type<'cx, 'gcx, 'tcx>(
126 selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
127 obligation: &PolyProjectionObligation<'tcx>)
128 -> Result<Option<Vec<PredicateObligation<'tcx>>>, MismatchedProjectionTypes<'tcx>>
130 debug!("poly_project_and_unify_type(obligation={:?})",
133 let infcx = selcx.infcx();
134 infcx.commit_if_ok(|snapshot| {
135 let (skol_predicate, skol_map) =
136 infcx.skolemize_late_bound_regions(&obligation.predicate, snapshot);
138 let skol_obligation = obligation.with(skol_predicate);
139 let r = match project_and_unify_type(selcx, &skol_obligation) {
141 let span = obligation.cause.span;
142 match infcx.leak_check(false, span, &skol_map, snapshot) {
143 Ok(()) => Ok(infcx.plug_leaks(skol_map, snapshot, result)),
144 Err(e) => Err(MismatchedProjectionTypes { err: e }),
156 /// Evaluates constraints of the form:
158 /// <T as Trait>::U == V
160 /// If successful, this may result in additional obligations.
161 fn project_and_unify_type<'cx, 'gcx, 'tcx>(
162 selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
163 obligation: &ProjectionObligation<'tcx>)
164 -> Result<Option<Vec<PredicateObligation<'tcx>>>, MismatchedProjectionTypes<'tcx>>
166 debug!("project_and_unify_type(obligation={:?})",
169 let Normalized { value: normalized_ty, mut obligations } =
170 match opt_normalize_projection_type(selcx,
171 obligation.param_env,
172 obligation.predicate.projection_ty,
173 obligation.cause.clone(),
174 obligation.recursion_depth) {
176 None => return Ok(None),
179 debug!("project_and_unify_type: normalized_ty={:?} obligations={:?}",
183 let infcx = selcx.infcx();
184 match infcx.at(&obligation.cause, obligation.param_env)
185 .eq(normalized_ty, obligation.predicate.ty) {
186 Ok(InferOk { obligations: inferred_obligations, value: () }) => {
187 obligations.extend(inferred_obligations);
188 Ok(Some(obligations))
190 Err(err) => Err(MismatchedProjectionTypes { err: err }),
194 /// Normalizes any associated type projections in `value`, replacing
195 /// them with a fully resolved type where possible. The return value
196 /// combines the normalized result and any additional obligations that
197 /// were incurred as result.
198 pub fn normalize<'a, 'b, 'gcx, 'tcx, T>(selcx: &'a mut SelectionContext<'b, 'gcx, 'tcx>,
199 param_env: ty::ParamEnv<'tcx>,
200 cause: ObligationCause<'tcx>,
202 -> Normalized<'tcx, T>
203 where T : TypeFoldable<'tcx>
205 normalize_with_depth(selcx, param_env, cause, 0, value)
208 /// As `normalize`, but with a custom depth.
209 pub fn normalize_with_depth<'a, 'b, 'gcx, 'tcx, T>(
210 selcx: &'a mut SelectionContext<'b, 'gcx, 'tcx>,
211 param_env: ty::ParamEnv<'tcx>,
212 cause: ObligationCause<'tcx>,
215 -> Normalized<'tcx, T>
217 where T : TypeFoldable<'tcx>
219 debug!("normalize_with_depth(depth={}, value={:?})", depth, value);
220 let mut normalizer = AssociatedTypeNormalizer::new(selcx, param_env, cause, depth);
221 let result = normalizer.fold(value);
222 debug!("normalize_with_depth: depth={} result={:?} with {} obligations",
223 depth, result, normalizer.obligations.len());
224 debug!("normalize_with_depth: depth={} obligations={:?}",
225 depth, normalizer.obligations);
228 obligations: normalizer.obligations,
232 struct AssociatedTypeNormalizer<'a, 'b: 'a, 'gcx: 'b+'tcx, 'tcx: 'b> {
233 selcx: &'a mut SelectionContext<'b, 'gcx, 'tcx>,
234 param_env: ty::ParamEnv<'tcx>,
235 cause: ObligationCause<'tcx>,
236 obligations: Vec<PredicateObligation<'tcx>>,
240 impl<'a, 'b, 'gcx, 'tcx> AssociatedTypeNormalizer<'a, 'b, 'gcx, 'tcx> {
241 fn new(selcx: &'a mut SelectionContext<'b, 'gcx, 'tcx>,
242 param_env: ty::ParamEnv<'tcx>,
243 cause: ObligationCause<'tcx>,
245 -> AssociatedTypeNormalizer<'a, 'b, 'gcx, 'tcx>
247 AssociatedTypeNormalizer {
249 param_env: param_env,
256 fn fold<T:TypeFoldable<'tcx>>(&mut self, value: &T) -> T {
257 let value = self.selcx.infcx().resolve_type_vars_if_possible(value);
259 if !value.has_projection_types() {
262 value.fold_with(self)
267 impl<'a, 'b, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for AssociatedTypeNormalizer<'a, 'b, 'gcx, 'tcx> {
268 fn tcx<'c>(&'c self) -> TyCtxt<'c, 'gcx, 'tcx> {
272 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
273 // We don't want to normalize associated types that occur inside of region
274 // binders, because they may contain bound regions, and we can't cope with that.
278 // for<'a> fn(<T as Foo<&'a>>::A)
280 // Instead of normalizing `<T as Foo<&'a>>::A` here, we'll
281 // normalize it when we instantiate those bound regions (which
282 // should occur eventually).
284 let ty = ty.super_fold_with(self);
286 ty::TyAnon(def_id, substs) if !substs.has_escaping_regions() => { // (*)
287 // Only normalize `impl Trait` after type-checking, usually in trans.
288 match self.param_env.reveal {
289 Reveal::UserFacing => ty,
292 let generic_ty = self.tcx().type_of(def_id);
293 let concrete_ty = generic_ty.subst(self.tcx(), substs);
294 self.fold_ty(concrete_ty)
299 ty::TyProjection(ref data) if !data.has_escaping_regions() => { // (*)
301 // (*) This is kind of hacky -- we need to be able to
302 // handle normalization within binders because
303 // otherwise we wind up a need to normalize when doing
304 // trait matching (since you can have a trait
305 // obligation like `for<'a> T::B : Fn(&'a int)`), but
306 // we can't normalize with bound regions in scope. So
307 // far now we just ignore binders but only normalize
308 // if all bound regions are gone (and then we still
309 // have to renormalize whenever we instantiate a
310 // binder). It would be better to normalize in a
311 // binding-aware fashion.
313 let Normalized { value: normalized_ty, obligations } =
314 normalize_projection_type(self.selcx,
319 debug!("AssociatedTypeNormalizer: depth={} normalized {:?} to {:?} \
320 with {} add'l obligations",
321 self.depth, ty, normalized_ty, obligations.len());
322 self.obligations.extend(obligations);
334 pub struct Normalized<'tcx,T> {
336 pub obligations: Vec<PredicateObligation<'tcx>>,
339 pub type NormalizedTy<'tcx> = Normalized<'tcx, Ty<'tcx>>;
341 impl<'tcx,T> Normalized<'tcx,T> {
342 pub fn with<U>(self, value: U) -> Normalized<'tcx,U> {
343 Normalized { value: value, obligations: self.obligations }
347 /// The guts of `normalize`: normalize a specific projection like `<T
348 /// as Trait>::Item`. The result is always a type (and possibly
349 /// additional obligations). If ambiguity arises, which implies that
350 /// there are unresolved type variables in the projection, we will
351 /// substitute a fresh type variable `$X` and generate a new
352 /// obligation `<T as Trait>::Item == $X` for later.
353 pub fn normalize_projection_type<'a, 'b, 'gcx, 'tcx>(
354 selcx: &'a mut SelectionContext<'b, 'gcx, 'tcx>,
355 param_env: ty::ParamEnv<'tcx>,
356 projection_ty: ty::ProjectionTy<'tcx>,
357 cause: ObligationCause<'tcx>,
359 -> NormalizedTy<'tcx>
361 opt_normalize_projection_type(selcx, param_env, projection_ty.clone(), cause.clone(), depth)
362 .unwrap_or_else(move || {
363 // if we bottom out in ambiguity, create a type variable
364 // and a deferred predicate to resolve this when more type
365 // information is available.
367 let tcx = selcx.infcx().tcx;
368 let def_id = tcx.associated_items(projection_ty.trait_ref.def_id).find(|i|
369 i.name == projection_ty.item_name(tcx) && i.kind == ty::AssociatedKind::Type
370 ).map(|i| i.def_id).unwrap();
371 let ty_var = selcx.infcx().next_ty_var(
372 TypeVariableOrigin::NormalizeProjectionType(tcx.def_span(def_id)));
373 let projection = ty::Binder(ty::ProjectionPredicate {
374 projection_ty: projection_ty,
377 let obligation = Obligation::with_depth(
378 cause, depth + 1, param_env, projection.to_predicate());
381 obligations: vec![obligation]
386 /// The guts of `normalize`: normalize a specific projection like `<T
387 /// as Trait>::Item`. The result is always a type (and possibly
388 /// additional obligations). Returns `None` in the case of ambiguity,
389 /// which indicates that there are unbound type variables.
390 fn opt_normalize_projection_type<'a, 'b, 'gcx, 'tcx>(
391 selcx: &'a mut SelectionContext<'b, 'gcx, 'tcx>,
392 param_env: ty::ParamEnv<'tcx>,
393 projection_ty: ty::ProjectionTy<'tcx>,
394 cause: ObligationCause<'tcx>,
396 -> Option<NormalizedTy<'tcx>>
398 let infcx = selcx.infcx();
400 let projection_ty = infcx.resolve_type_vars_if_possible(&projection_ty);
402 debug!("opt_normalize_projection_type(\
403 projection_ty={:?}, \
408 // FIXME(#20304) For now, I am caching here, which is good, but it
409 // means we don't capture the type variables that are created in
410 // the case of ambiguity. Which means we may create a large stream
411 // of such variables. OTOH, if we move the caching up a level, we
412 // would not benefit from caching when proving `T: Trait<U=Foo>`
413 // bounds. It might be the case that we want two distinct caches,
414 // or else another kind of cache entry.
416 match infcx.projection_cache.borrow_mut().try_start(projection_ty) {
418 Err(ProjectionCacheEntry::Ambiguous) => {
419 // If we found ambiguity the last time, that generally
420 // means we will continue to do so until some type in the
421 // key changes (and we know it hasn't, because we just
422 // fully resolved it). One exception though is closure
423 // types, which can transition from having a fixed kind to
424 // no kind with no visible change in the key.
426 // FIXME(#32286) refactor this so that closure type
428 debug!("opt_normalize_projection_type: \
429 found cache entry: ambiguous");
430 if !projection_ty.has_closure_types() {
434 Err(ProjectionCacheEntry::InProgress) => {
435 // If while normalized A::B, we are asked to normalize
436 // A::B, just return A::B itself. This is a conservative
437 // answer, in the sense that A::B *is* clearly equivalent
438 // to A::B, though there may be a better value we can
441 // Under lazy normalization, this can arise when
442 // bootstrapping. That is, imagine an environment with a
443 // where-clause like `A::B == u32`. Now, if we are asked
444 // to normalize `A::B`, we will want to check the
445 // where-clauses in scope. So we will try to unify `A::B`
446 // with `A::B`, which can trigger a recursive
447 // normalization. In that case, I think we will want this code:
450 // let ty = selcx.tcx().mk_projection(projection_ty.trait_ref,
451 // projection_ty.item_name(tcx);
452 // return Some(NormalizedTy { value: v, obligations: vec![] });
455 debug!("opt_normalize_projection_type: \
456 found cache entry: in-progress");
458 // But for now, let's classify this as an overflow:
459 let recursion_limit = selcx.tcx().sess.recursion_limit.get();
460 let obligation = Obligation::with_depth(cause.clone(),
464 selcx.infcx().report_overflow_error(&obligation, false);
466 Err(ProjectionCacheEntry::NormalizedTy(ty)) => {
467 // If we find the value in the cache, then the obligations
468 // have already been returned from the previous entry (and
469 // should therefore have been honored).
470 debug!("opt_normalize_projection_type: \
471 found normalized ty `{:?}`",
473 return Some(NormalizedTy { value: ty, obligations: vec![] });
475 Err(ProjectionCacheEntry::Error) => {
476 debug!("opt_normalize_projection_type: \
478 return Some(normalize_to_error(selcx, param_env, projection_ty, cause, depth));
482 let obligation = Obligation::with_depth(cause.clone(), depth, param_env, projection_ty);
483 match project_type(selcx, &obligation) {
484 Ok(ProjectedTy::Progress(Progress { ty: projected_ty,
487 // if projection succeeded, then what we get out of this
488 // is also non-normalized (consider: it was derived from
489 // an impl, where-clause etc) and hence we must
492 debug!("opt_normalize_projection_type: \
502 let result = if projected_ty.has_projection_types() {
503 let mut normalizer = AssociatedTypeNormalizer::new(selcx,
507 let normalized_ty = normalizer.fold(&projected_ty);
509 debug!("opt_normalize_projection_type: \
510 normalized_ty={:?} depth={}",
514 obligations.extend(normalizer.obligations);
516 value: normalized_ty,
517 obligations: obligations,
522 obligations: obligations,
525 infcx.projection_cache.borrow_mut()
526 .complete(projection_ty, &result, cacheable);
529 Ok(ProjectedTy::NoProgress(projected_ty)) => {
530 debug!("opt_normalize_projection_type: \
531 projected_ty={:?} no progress",
533 let result = Normalized {
537 infcx.projection_cache.borrow_mut()
538 .complete(projection_ty, &result, true);
541 Err(ProjectionTyError::TooManyCandidates) => {
542 debug!("opt_normalize_projection_type: \
543 too many candidates");
544 infcx.projection_cache.borrow_mut()
545 .ambiguous(projection_ty);
548 Err(ProjectionTyError::TraitSelectionError(_)) => {
549 debug!("opt_normalize_projection_type: ERROR");
550 // if we got an error processing the `T as Trait` part,
551 // just return `ty::err` but add the obligation `T :
552 // Trait`, which when processed will cause the error to be
555 infcx.projection_cache.borrow_mut()
556 .error(projection_ty);
557 Some(normalize_to_error(selcx, param_env, projection_ty, cause, depth))
562 /// If we are projecting `<T as Trait>::Item`, but `T: Trait` does not
563 /// hold. In various error cases, we cannot generate a valid
564 /// normalized projection. Therefore, we create an inference variable
565 /// return an associated obligation that, when fulfilled, will lead to
568 /// Note that we used to return `TyError` here, but that was quite
569 /// dubious -- the premise was that an error would *eventually* be
570 /// reported, when the obligation was processed. But in general once
571 /// you see a `TyError` you are supposed to be able to assume that an
572 /// error *has been* reported, so that you can take whatever heuristic
573 /// paths you want to take. To make things worse, it was possible for
574 /// cycles to arise, where you basically had a setup like `<MyType<$0>
575 /// as Trait>::Foo == $0`. Here, normalizing `<MyType<$0> as
576 /// Trait>::Foo> to `[type error]` would lead to an obligation of
577 /// `<MyType<[type error]> as Trait>::Foo`. We are supposed to report
578 /// an error for this obligation, but we legitimately should not,
579 /// because it contains `[type error]`. Yuck! (See issue #29857 for
580 /// one case where this arose.)
581 fn normalize_to_error<'a, 'gcx, 'tcx>(selcx: &mut SelectionContext<'a, 'gcx, 'tcx>,
582 param_env: ty::ParamEnv<'tcx>,
583 projection_ty: ty::ProjectionTy<'tcx>,
584 cause: ObligationCause<'tcx>,
586 -> NormalizedTy<'tcx>
588 let trait_ref = projection_ty.trait_ref.to_poly_trait_ref();
589 let trait_obligation = Obligation { cause: cause,
590 recursion_depth: depth,
592 predicate: trait_ref.to_predicate() };
593 let tcx = selcx.infcx().tcx;
594 let def_id = tcx.associated_items(projection_ty.trait_ref.def_id).find(|i|
595 i.name == projection_ty.item_name(tcx) && i.kind == ty::AssociatedKind::Type
596 ).map(|i| i.def_id).unwrap();
597 let new_value = selcx.infcx().next_ty_var(
598 TypeVariableOrigin::NormalizeProjectionType(tcx.def_span(def_id)));
601 obligations: vec![trait_obligation]
605 enum ProjectedTy<'tcx> {
606 Progress(Progress<'tcx>),
607 NoProgress(Ty<'tcx>),
610 struct Progress<'tcx> {
612 obligations: Vec<PredicateObligation<'tcx>>,
616 impl<'tcx> Progress<'tcx> {
617 fn error<'a,'gcx>(tcx: TyCtxt<'a,'gcx,'tcx>) -> Self {
625 fn with_addl_obligations(mut self,
626 mut obligations: Vec<PredicateObligation<'tcx>>)
628 debug!("with_addl_obligations: self.obligations.len={} obligations.len={}",
629 self.obligations.len(), obligations.len());
631 debug!("with_addl_obligations: self.obligations={:?} obligations={:?}",
632 self.obligations, obligations);
634 self.obligations.append(&mut obligations);
639 /// Compute the result of a projection type (if we can).
642 /// - `obligation` must be fully normalized
643 fn project_type<'cx, 'gcx, 'tcx>(
644 selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
645 obligation: &ProjectionTyObligation<'tcx>)
646 -> Result<ProjectedTy<'tcx>, ProjectionTyError<'tcx>>
648 debug!("project(obligation={:?})",
651 let recursion_limit = selcx.tcx().sess.recursion_limit.get();
652 if obligation.recursion_depth >= recursion_limit {
653 debug!("project: overflow!");
654 selcx.infcx().report_overflow_error(&obligation, true);
657 let obligation_trait_ref = &obligation.predicate.trait_ref;
659 debug!("project: obligation_trait_ref={:?}", obligation_trait_ref);
661 if obligation_trait_ref.references_error() {
662 return Ok(ProjectedTy::Progress(Progress::error(selcx.tcx())));
665 let mut candidates = ProjectionTyCandidateSet {
670 assemble_candidates_from_param_env(selcx,
672 &obligation_trait_ref,
675 assemble_candidates_from_trait_def(selcx,
677 &obligation_trait_ref,
680 if let Err(e) = assemble_candidates_from_impls(selcx,
682 &obligation_trait_ref,
684 return Err(ProjectionTyError::TraitSelectionError(e));
687 debug!("{} candidates, ambiguous={}",
688 candidates.vec.len(),
689 candidates.ambiguous);
691 // Inherent ambiguity that prevents us from even enumerating the
693 if candidates.ambiguous {
694 return Err(ProjectionTyError::TooManyCandidates);
699 // Note: `candidates.vec` seems to be on the critical path of the
700 // compiler. Replacing it with an hash set was also tried, which would
701 // render the following dedup unnecessary. It led to cleaner code but
702 // prolonged compiling time of `librustc` from 5m30s to 6m in one test, or
703 // ~9% performance lost.
704 if candidates.vec.len() > 1 {
706 while i < candidates.vec.len() {
707 let has_dup = (0..i).any(|j| candidates.vec[i] == candidates.vec[j]);
709 candidates.vec.swap_remove(i);
716 // Prefer where-clauses. As in select, if there are multiple
717 // candidates, we prefer where-clause candidates over impls. This
718 // may seem a bit surprising, since impls are the source of
719 // "truth" in some sense, but in fact some of the impls that SEEM
720 // applicable are not, because of nested obligations. Where
721 // clauses are the safer choice. See the comment on
722 // `select::SelectionCandidate` and #21974 for more details.
723 if candidates.vec.len() > 1 {
724 debug!("retaining param-env candidates only from {:?}", candidates.vec);
725 candidates.vec.retain(|c| match *c {
726 ProjectionTyCandidate::ParamEnv(..) => true,
727 ProjectionTyCandidate::TraitDef(..) |
728 ProjectionTyCandidate::Select => false,
730 debug!("resulting candidate set: {:?}", candidates.vec);
731 if candidates.vec.len() != 1 {
732 return Err(ProjectionTyError::TooManyCandidates);
736 assert!(candidates.vec.len() <= 1);
738 match candidates.vec.pop() {
740 Ok(ProjectedTy::Progress(
741 confirm_candidate(selcx,
743 &obligation_trait_ref,
747 Ok(ProjectedTy::NoProgress(
748 selcx.tcx().mk_projection(
749 obligation.predicate.trait_ref.clone(),
750 obligation.predicate.item_name(selcx.tcx()))))
755 /// The first thing we have to do is scan through the parameter
756 /// environment to see whether there are any projection predicates
757 /// there that can answer this question.
758 fn assemble_candidates_from_param_env<'cx, 'gcx, 'tcx>(
759 selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
760 obligation: &ProjectionTyObligation<'tcx>,
761 obligation_trait_ref: &ty::TraitRef<'tcx>,
762 candidate_set: &mut ProjectionTyCandidateSet<'tcx>)
764 debug!("assemble_candidates_from_param_env(..)");
765 assemble_candidates_from_predicates(selcx,
767 obligation_trait_ref,
769 ProjectionTyCandidate::ParamEnv,
770 obligation.param_env.caller_bounds.iter().cloned());
773 /// In the case of a nested projection like <<A as Foo>::FooT as Bar>::BarT, we may find
774 /// that the definition of `Foo` has some clues:
778 /// type FooT : Bar<BarT=i32>
782 /// Here, for example, we could conclude that the result is `i32`.
783 fn assemble_candidates_from_trait_def<'cx, 'gcx, 'tcx>(
784 selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
785 obligation: &ProjectionTyObligation<'tcx>,
786 obligation_trait_ref: &ty::TraitRef<'tcx>,
787 candidate_set: &mut ProjectionTyCandidateSet<'tcx>)
789 debug!("assemble_candidates_from_trait_def(..)");
791 // Check whether the self-type is itself a projection.
792 let (def_id, substs) = match obligation_trait_ref.self_ty().sty {
793 ty::TyProjection(ref data) => {
794 (data.trait_ref.def_id, data.trait_ref.substs)
796 ty::TyAnon(def_id, substs) => (def_id, substs),
797 ty::TyInfer(ty::TyVar(_)) => {
798 // If the self-type is an inference variable, then it MAY wind up
799 // being a projected type, so induce an ambiguity.
800 candidate_set.ambiguous = true;
806 // If so, extract what we know from the trait and try to come up with a good answer.
807 let trait_predicates = selcx.tcx().predicates_of(def_id);
808 let bounds = trait_predicates.instantiate(selcx.tcx(), substs);
809 let bounds = elaborate_predicates(selcx.tcx(), bounds.predicates);
810 assemble_candidates_from_predicates(selcx,
812 obligation_trait_ref,
814 ProjectionTyCandidate::TraitDef,
818 fn assemble_candidates_from_predicates<'cx, 'gcx, 'tcx, I>(
819 selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
820 obligation: &ProjectionTyObligation<'tcx>,
821 obligation_trait_ref: &ty::TraitRef<'tcx>,
822 candidate_set: &mut ProjectionTyCandidateSet<'tcx>,
823 ctor: fn(ty::PolyProjectionPredicate<'tcx>) -> ProjectionTyCandidate<'tcx>,
825 where I: IntoIterator<Item=ty::Predicate<'tcx>>
827 debug!("assemble_candidates_from_predicates(obligation={:?})",
829 let infcx = selcx.infcx();
830 for predicate in env_predicates {
831 debug!("assemble_candidates_from_predicates: predicate={:?}",
834 ty::Predicate::Projection(ref data) => {
835 let tcx = selcx.tcx();
836 let same_name = data.item_name(tcx) == obligation.predicate.item_name(tcx);
838 let is_match = same_name && infcx.probe(|_| {
839 let data_poly_trait_ref =
840 data.to_poly_trait_ref();
841 let obligation_poly_trait_ref =
842 obligation_trait_ref.to_poly_trait_ref();
843 infcx.at(&obligation.cause, obligation.param_env)
844 .sup(obligation_poly_trait_ref, data_poly_trait_ref)
845 .map(|InferOk { obligations: _, value: () }| {
846 // FIXME(#32730) -- do we need to take obligations
847 // into account in any way? At the moment, no.
852 debug!("assemble_candidates_from_predicates: candidate={:?} \
853 is_match={} same_name={}",
854 data, is_match, same_name);
857 candidate_set.vec.push(ctor(data.clone()));
865 fn assemble_candidates_from_impls<'cx, 'gcx, 'tcx>(
866 selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
867 obligation: &ProjectionTyObligation<'tcx>,
868 obligation_trait_ref: &ty::TraitRef<'tcx>,
869 candidate_set: &mut ProjectionTyCandidateSet<'tcx>)
870 -> Result<(), SelectionError<'tcx>>
872 // If we are resolving `<T as TraitRef<...>>::Item == Type`,
873 // start out by selecting the predicate `T as TraitRef<...>`:
874 let poly_trait_ref = obligation_trait_ref.to_poly_trait_ref();
875 let trait_obligation = obligation.with(poly_trait_ref.to_poly_trait_predicate());
876 selcx.infcx().probe(|_| {
877 let vtable = match selcx.select(&trait_obligation) {
878 Ok(Some(vtable)) => vtable,
880 candidate_set.ambiguous = true;
884 debug!("assemble_candidates_from_impls: selection error {:?}",
891 super::VtableClosure(_) |
892 super::VtableFnPointer(_) |
893 super::VtableObject(_) => {
894 debug!("assemble_candidates_from_impls: vtable={:?}",
897 candidate_set.vec.push(ProjectionTyCandidate::Select);
899 super::VtableImpl(ref impl_data) => {
900 // We have to be careful when projecting out of an
901 // impl because of specialization. If we are not in
902 // trans (i.e., projection mode is not "any"), and the
903 // impl's type is declared as default, then we disable
904 // projection (even if the trait ref is fully
905 // monomorphic). In the case where trait ref is not
906 // fully monomorphic (i.e., includes type parameters),
907 // this is because those type parameters may
908 // ultimately be bound to types from other crates that
909 // may have specialized impls we can't see. In the
910 // case where the trait ref IS fully monomorphic, this
911 // is a policy decision that we made in the RFC in
912 // order to preserve flexibility for the crate that
913 // defined the specializable impl to specialize later
914 // for existing types.
916 // In either case, we handle this by not adding a
917 // candidate for an impl if it contains a `default`
919 let node_item = assoc_ty_def(selcx,
920 impl_data.impl_def_id,
921 obligation.predicate.item_name(selcx.tcx()));
923 let is_default = if node_item.node.is_from_trait() {
924 // If true, the impl inherited a `type Foo = Bar`
925 // given in the trait, which is implicitly default.
926 // Otherwise, the impl did not specify `type` and
927 // neither did the trait:
930 // trait Foo { type T; }
931 // impl Foo for Bar { }
934 // This is an error, but it will be
935 // reported in `check_impl_items_against_trait`.
936 // We accept it here but will flag it as
937 // an error when we confirm the candidate
938 // (which will ultimately lead to `normalize_to_error`
940 node_item.item.defaultness.has_value()
942 node_item.item.defaultness.is_default() ||
943 selcx.tcx().impl_is_default(node_item.node.def_id())
946 // Only reveal a specializable default if we're past type-checking
947 // and the obligations is monomorphic, otherwise passes such as
948 // transmute checking and polymorphic MIR optimizations could
949 // get a result which isn't correct for all monomorphizations.
950 let new_candidate = if !is_default {
951 Some(ProjectionTyCandidate::Select)
952 } else if obligation.param_env.reveal == Reveal::All {
953 assert!(!poly_trait_ref.needs_infer());
954 if !poly_trait_ref.needs_subst() {
955 Some(ProjectionTyCandidate::Select)
963 candidate_set.vec.extend(new_candidate);
965 super::VtableParam(..) => {
966 // This case tell us nothing about the value of an
967 // associated type. Consider:
970 // trait SomeTrait { type Foo; }
971 // fn foo<T:SomeTrait>(...) { }
974 // If the user writes `<T as SomeTrait>::Foo`, then the `T
975 // : SomeTrait` binding does not help us decide what the
976 // type `Foo` is (at least, not more specifically than
977 // what we already knew).
979 // But wait, you say! What about an example like this:
982 // fn bar<T:SomeTrait<Foo=usize>>(...) { ... }
985 // Doesn't the `T : Sometrait<Foo=usize>` predicate help
986 // resolve `T::Foo`? And of course it does, but in fact
987 // that single predicate is desugared into two predicates
988 // in the compiler: a trait predicate (`T : SomeTrait`) and a
989 // projection. And the projection where clause is handled
990 // in `assemble_candidates_from_param_env`.
992 super::VtableDefaultImpl(..) |
993 super::VtableBuiltin(..) => {
994 // These traits have no associated types.
996 obligation.cause.span,
997 "Cannot project an associated type from `{:?}`",
1006 fn confirm_candidate<'cx, 'gcx, 'tcx>(
1007 selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
1008 obligation: &ProjectionTyObligation<'tcx>,
1009 obligation_trait_ref: &ty::TraitRef<'tcx>,
1010 candidate: ProjectionTyCandidate<'tcx>)
1013 debug!("confirm_candidate(candidate={:?}, obligation={:?})",
1018 ProjectionTyCandidate::ParamEnv(poly_projection) |
1019 ProjectionTyCandidate::TraitDef(poly_projection) => {
1020 confirm_param_env_candidate(selcx, obligation, poly_projection)
1023 ProjectionTyCandidate::Select => {
1024 confirm_select_candidate(selcx, obligation, obligation_trait_ref)
1029 fn confirm_select_candidate<'cx, 'gcx, 'tcx>(
1030 selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
1031 obligation: &ProjectionTyObligation<'tcx>,
1032 obligation_trait_ref: &ty::TraitRef<'tcx>)
1035 let poly_trait_ref = obligation_trait_ref.to_poly_trait_ref();
1036 let trait_obligation = obligation.with(poly_trait_ref.to_poly_trait_predicate());
1037 let vtable = match selcx.select(&trait_obligation) {
1038 Ok(Some(vtable)) => vtable,
1041 obligation.cause.span,
1042 "Failed to select `{:?}`",
1048 super::VtableImpl(data) =>
1049 confirm_impl_candidate(selcx, obligation, data),
1050 super::VtableClosure(data) =>
1051 confirm_closure_candidate(selcx, obligation, data),
1052 super::VtableFnPointer(data) =>
1053 confirm_fn_pointer_candidate(selcx, obligation, data),
1054 super::VtableObject(_) =>
1055 confirm_object_candidate(selcx, obligation, obligation_trait_ref),
1056 super::VtableDefaultImpl(..) |
1057 super::VtableParam(..) |
1058 super::VtableBuiltin(..) =>
1059 // we don't create Select candidates with this kind of resolution
1061 obligation.cause.span,
1062 "Cannot project an associated type from `{:?}`",
1067 fn confirm_object_candidate<'cx, 'gcx, 'tcx>(
1068 selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
1069 obligation: &ProjectionTyObligation<'tcx>,
1070 obligation_trait_ref: &ty::TraitRef<'tcx>)
1073 let self_ty = obligation_trait_ref.self_ty();
1074 let object_ty = selcx.infcx().shallow_resolve(self_ty);
1075 debug!("confirm_object_candidate(object_ty={:?})",
1077 let data = match object_ty.sty {
1078 ty::TyDynamic(ref data, ..) => data,
1081 obligation.cause.span,
1082 "confirm_object_candidate called with non-object: {:?}",
1086 let env_predicates = data.projection_bounds().map(|p| {
1087 p.with_self_ty(selcx.tcx(), object_ty).to_predicate()
1089 let env_predicate = {
1090 let env_predicates = elaborate_predicates(selcx.tcx(), env_predicates);
1092 // select only those projections that are actually projecting an
1093 // item with the correct name
1094 let tcx = selcx.tcx();
1095 let env_predicates = env_predicates.filter_map(|p| match p {
1096 ty::Predicate::Projection(data) =>
1097 if data.item_name(tcx) == obligation.predicate.item_name(tcx) {
1105 // select those with a relevant trait-ref
1106 let mut env_predicates = env_predicates.filter(|data| {
1107 let data_poly_trait_ref = data.to_poly_trait_ref();
1108 let obligation_poly_trait_ref = obligation_trait_ref.to_poly_trait_ref();
1109 selcx.infcx().probe(|_| {
1110 selcx.infcx().at(&obligation.cause, obligation.param_env)
1111 .sup(obligation_poly_trait_ref, data_poly_trait_ref)
1116 // select the first matching one; there really ought to be one or
1117 // else the object type is not WF, since an object type should
1118 // include all of its projections explicitly
1119 match env_predicates.next() {
1120 Some(env_predicate) => env_predicate,
1122 debug!("confirm_object_candidate: no env-predicate \
1123 found in object type `{:?}`; ill-formed",
1125 return Progress::error(selcx.tcx());
1130 confirm_param_env_candidate(selcx, obligation, env_predicate)
1133 fn confirm_fn_pointer_candidate<'cx, 'gcx, 'tcx>(
1134 selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
1135 obligation: &ProjectionTyObligation<'tcx>,
1136 fn_pointer_vtable: VtableFnPointerData<'tcx, PredicateObligation<'tcx>>)
1139 let fn_type = selcx.infcx().shallow_resolve(fn_pointer_vtable.fn_ty);
1140 let sig = fn_type.fn_sig();
1141 confirm_callable_candidate(selcx, obligation, sig, util::TupleArgumentsFlag::Yes)
1142 .with_addl_obligations(fn_pointer_vtable.nested)
1145 fn confirm_closure_candidate<'cx, 'gcx, 'tcx>(
1146 selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
1147 obligation: &ProjectionTyObligation<'tcx>,
1148 vtable: VtableClosureData<'tcx, PredicateObligation<'tcx>>)
1151 let closure_typer = selcx.closure_typer();
1152 let closure_type = closure_typer.closure_type(vtable.closure_def_id)
1153 .subst(selcx.tcx(), vtable.substs.substs);
1155 value: closure_type,
1157 } = normalize_with_depth(selcx,
1158 obligation.param_env,
1159 obligation.cause.clone(),
1160 obligation.recursion_depth+1,
1163 debug!("confirm_closure_candidate: obligation={:?},closure_type={:?},obligations={:?}",
1168 confirm_callable_candidate(selcx,
1171 util::TupleArgumentsFlag::No)
1172 .with_addl_obligations(vtable.nested)
1173 .with_addl_obligations(obligations)
1176 fn confirm_callable_candidate<'cx, 'gcx, 'tcx>(
1177 selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
1178 obligation: &ProjectionTyObligation<'tcx>,
1179 fn_sig: ty::PolyFnSig<'tcx>,
1180 flag: util::TupleArgumentsFlag)
1183 let tcx = selcx.tcx();
1185 debug!("confirm_callable_candidate({:?},{:?})",
1189 // the `Output` associated type is declared on `FnOnce`
1190 let fn_once_def_id = tcx.lang_items.fn_once_trait().unwrap();
1192 // Note: we unwrap the binder here but re-create it below (1)
1193 let ty::Binder((trait_ref, ret_type)) =
1194 tcx.closure_trait_ref_and_return_type(fn_once_def_id,
1195 obligation.predicate.trait_ref.self_ty(),
1199 let predicate = ty::Binder(ty::ProjectionPredicate { // (1) recreate binder here
1200 projection_ty: ty::ProjectionTy::from_ref_and_name(
1203 Symbol::intern(FN_OUTPUT_NAME),
1208 confirm_param_env_candidate(selcx, obligation, predicate)
1211 fn confirm_param_env_candidate<'cx, 'gcx, 'tcx>(
1212 selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
1213 obligation: &ProjectionTyObligation<'tcx>,
1214 poly_projection: ty::PolyProjectionPredicate<'tcx>)
1217 let infcx = selcx.infcx();
1218 let cause = obligation.cause.clone();
1219 let param_env = obligation.param_env;
1220 let trait_ref = obligation.predicate.trait_ref;
1221 match infcx.match_poly_projection_predicate(cause, param_env, poly_projection, trait_ref) {
1222 Ok(InferOk { value: ty_match, obligations }) => {
1225 obligations: obligations,
1226 cacheable: ty_match.unconstrained_regions.is_empty(),
1231 obligation.cause.span,
1232 "Failed to unify obligation `{:?}` \
1233 with poly_projection `{:?}`: {:?}",
1241 fn confirm_impl_candidate<'cx, 'gcx, 'tcx>(
1242 selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
1243 obligation: &ProjectionTyObligation<'tcx>,
1244 impl_vtable: VtableImplData<'tcx, PredicateObligation<'tcx>>)
1247 let VtableImplData { substs, nested, impl_def_id } = impl_vtable;
1249 let tcx = selcx.tcx();
1250 let param_env = obligation.param_env;
1251 let assoc_ty = assoc_ty_def(selcx, impl_def_id, obligation.predicate.item_name(tcx));
1253 let ty = if !assoc_ty.item.defaultness.has_value() {
1254 // This means that the impl is missing a definition for the
1255 // associated type. This error will be reported by the type
1256 // checker method `check_impl_items_against_trait`, so here we
1257 // just return TyError.
1258 debug!("confirm_impl_candidate: no associated type {:?} for {:?}",
1260 obligation.predicate.trait_ref);
1263 tcx.type_of(assoc_ty.item.def_id)
1265 let substs = translate_substs(selcx.infcx(), param_env, impl_def_id, substs, assoc_ty.node);
1267 ty: ty.subst(tcx, substs),
1268 obligations: nested,
1273 /// Locate the definition of an associated type in the specialization hierarchy,
1274 /// starting from the given impl.
1276 /// Based on the "projection mode", this lookup may in fact only examine the
1277 /// topmost impl. See the comments for `Reveal` for more details.
1278 fn assoc_ty_def<'cx, 'gcx, 'tcx>(
1279 selcx: &SelectionContext<'cx, 'gcx, 'tcx>,
1281 assoc_ty_name: ast::Name)
1282 -> specialization_graph::NodeItem<ty::AssociatedItem>
1284 let tcx = selcx.tcx();
1285 let trait_def_id = tcx.impl_trait_ref(impl_def_id).unwrap().def_id;
1286 let trait_def = tcx.trait_def(trait_def_id);
1288 // This function may be called while we are still building the
1289 // specialization graph that is queried below (via TraidDef::ancestors()),
1290 // so, in order to avoid unnecessary infinite recursion, we manually look
1291 // for the associated item at the given impl.
1292 // If there is no such item in that impl, this function will fail with a
1293 // cycle error if the specialization graph is currently being built.
1294 let impl_node = specialization_graph::Node::Impl(impl_def_id);
1295 for item in impl_node.items(tcx) {
1296 if item.kind == ty::AssociatedKind::Type && item.name == assoc_ty_name {
1297 return specialization_graph::NodeItem {
1298 node: specialization_graph::Node::Impl(impl_def_id),
1304 if let Some(assoc_item) = trait_def
1305 .ancestors(tcx, impl_def_id)
1306 .defs(tcx, assoc_ty_name, ty::AssociatedKind::Type)
1310 // This is saying that neither the trait nor
1311 // the impl contain a definition for this
1312 // associated type. Normally this situation
1313 // could only arise through a compiler bug --
1314 // if the user wrote a bad item name, it
1315 // should have failed in astconv.
1316 bug!("No associated type `{}` for {}",
1318 tcx.item_path_str(impl_def_id))
1324 pub struct ProjectionCache<'tcx> {
1325 map: SnapshotMap<ty::ProjectionTy<'tcx>, ProjectionCacheEntry<'tcx>>,
1328 #[derive(Clone, Debug)]
1329 enum ProjectionCacheEntry<'tcx> {
1333 NormalizedTy(Ty<'tcx>),
1336 // NB: intentionally not Clone
1337 pub struct ProjectionCacheSnapshot {
1341 impl<'tcx> ProjectionCache<'tcx> {
1342 pub fn new() -> Self {
1344 map: SnapshotMap::new()
1348 pub fn snapshot(&mut self) -> ProjectionCacheSnapshot {
1349 ProjectionCacheSnapshot { snapshot: self.map.snapshot() }
1352 pub fn rollback_to(&mut self, snapshot: ProjectionCacheSnapshot) {
1353 self.map.rollback_to(snapshot.snapshot);
1356 pub fn rollback_skolemized(&mut self, snapshot: &ProjectionCacheSnapshot) {
1357 self.map.partial_rollback(&snapshot.snapshot, &|k| k.has_re_skol());
1360 pub fn commit(&mut self, snapshot: ProjectionCacheSnapshot) {
1361 self.map.commit(snapshot.snapshot);
1364 /// Try to start normalize `key`; returns an error if
1365 /// normalization already occured (this error corresponds to a
1366 /// cache hit, so it's actually a good thing).
1367 fn try_start(&mut self, key: ty::ProjectionTy<'tcx>)
1368 -> Result<(), ProjectionCacheEntry<'tcx>> {
1369 if let Some(entry) = self.map.get(&key) {
1370 return Err(entry.clone());
1373 self.map.insert(key, ProjectionCacheEntry::InProgress);
1377 /// Indicates that `key` was normalized to `value`. If `cacheable` is false,
1378 /// then this result is sadly not cacheable.
1379 fn complete(&mut self,
1380 key: ty::ProjectionTy<'tcx>,
1381 value: &NormalizedTy<'tcx>,
1383 let fresh_key = if cacheable {
1384 debug!("ProjectionCacheEntry::complete: adding cache entry: key={:?}, value={:?}",
1386 self.map.insert(key, ProjectionCacheEntry::NormalizedTy(value.value))
1388 debug!("ProjectionCacheEntry::complete: cannot cache: key={:?}, value={:?}",
1390 !self.map.remove(key)
1393 assert!(!fresh_key, "never started projecting `{:?}`", key);
1396 /// Indicates that trying to normalize `key` resulted in
1397 /// ambiguity. No point in trying it again then until we gain more
1398 /// type information (in which case, the "fully resolved" key will
1400 fn ambiguous(&mut self, key: ty::ProjectionTy<'tcx>) {
1401 let fresh = self.map.insert(key, ProjectionCacheEntry::Ambiguous);
1402 assert!(!fresh, "never started projecting `{:?}`", key);
1405 /// Indicates that trying to normalize `key` resulted in
1407 fn error(&mut self, key: ty::ProjectionTy<'tcx>) {
1408 let fresh = self.map.insert(key, ProjectionCacheEntry::Error);
1409 assert!(!fresh, "never started projecting `{:?}`", key);