1 //! Code for projecting associated types out of trait references.
3 use super::elaborate_predicates;
4 use super::specialization_graph;
5 use super::translate_substs;
7 use super::ObligationCause;
8 use super::PredicateObligation;
10 use super::SelectionContext;
11 use super::SelectionError;
12 use super::{VtableImplData, VtableClosureData, VtableGeneratorData, VtableFnPointerData};
15 use crate::hir::def_id::DefId;
16 use crate::infer::{InferCtxt, InferOk, LateBoundRegionConversionTime};
17 use crate::infer::type_variable::TypeVariableOrigin;
18 use crate::mir::interpret::{GlobalId};
19 use rustc_data_structures::snapshot_map::{Snapshot, SnapshotMap};
20 use syntax::ast::Ident;
21 use crate::ty::subst::{Subst, Substs};
22 use crate::ty::{self, ToPredicate, ToPolyTraitRef, Ty, TyCtxt};
23 use crate::ty::fold::{TypeFoldable, TypeFolder};
24 use crate::util::common::FN_OUTPUT_NAME;
26 /// Depending on the stage of compilation, we want projection to be
27 /// more or less conservative.
28 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
30 /// At type-checking time, we refuse to project any associated
31 /// type that is marked `default`. Non-`default` ("final") types
32 /// are always projected. This is necessary in general for
33 /// soundness of specialization. However, we *could* allow
34 /// projections in fully-monomorphic cases. We choose not to,
35 /// because we prefer for `default type` to force the type
36 /// definition to be treated abstractly by any consumers of the
37 /// impl. Concretely, that means that the following example will
45 /// impl<T> Assoc for T {
46 /// default type Output = bool;
50 /// let <() as Assoc>::Output = true;
54 /// At codegen time, all monomorphic projections will succeed.
55 /// Also, `impl Trait` is normalized to the concrete type,
56 /// which has to be already collected by type-checking.
58 /// NOTE: as `impl Trait`'s concrete type should *never*
59 /// be observable directly by the user, `Reveal::All`
60 /// should not be used by checks which may expose
61 /// type equality or type contents to the user.
62 /// There are some exceptions, e.g., around OIBITS and
63 /// transmute-checking, which expose some details, but
64 /// not the whole concrete type of the `impl Trait`.
68 pub type PolyProjectionObligation<'tcx> =
69 Obligation<'tcx, ty::PolyProjectionPredicate<'tcx>>;
71 pub type ProjectionObligation<'tcx> =
72 Obligation<'tcx, ty::ProjectionPredicate<'tcx>>;
74 pub type ProjectionTyObligation<'tcx> =
75 Obligation<'tcx, ty::ProjectionTy<'tcx>>;
77 /// When attempting to resolve `<T as TraitRef>::Name` ...
79 pub enum ProjectionTyError<'tcx> {
80 /// ...we found multiple sources of information and couldn't resolve the ambiguity.
83 /// ...an error occurred matching `T : TraitRef`
84 TraitSelectionError(SelectionError<'tcx>),
88 pub struct MismatchedProjectionTypes<'tcx> {
89 pub err: ty::error::TypeError<'tcx>
92 #[derive(PartialEq, Eq, Debug)]
93 enum ProjectionTyCandidate<'tcx> {
94 // from a where-clause in the env or object type
95 ParamEnv(ty::PolyProjectionPredicate<'tcx>),
97 // from the definition of `Trait` when you have something like <<A as Trait>::B as Trait2>::C
98 TraitDef(ty::PolyProjectionPredicate<'tcx>),
100 // from a "impl" (or a "pseudo-impl" returned by select)
101 Select(Selection<'tcx>),
104 enum ProjectionTyCandidateSet<'tcx> {
106 Single(ProjectionTyCandidate<'tcx>),
108 Error(SelectionError<'tcx>),
111 impl<'tcx> ProjectionTyCandidateSet<'tcx> {
112 fn mark_ambiguous(&mut self) {
113 *self = ProjectionTyCandidateSet::Ambiguous;
116 fn mark_error(&mut self, err: SelectionError<'tcx>) {
117 *self = ProjectionTyCandidateSet::Error(err);
120 // Returns true if the push was successful, or false if the candidate
121 // was discarded -- this could be because of ambiguity, or because
122 // a higher-priority candidate is already there.
123 fn push_candidate(&mut self, candidate: ProjectionTyCandidate<'tcx>) -> bool {
124 use self::ProjectionTyCandidateSet::*;
125 use self::ProjectionTyCandidate::*;
127 // This wacky variable is just used to try and
128 // make code readable and avoid confusing paths.
129 // It is assigned a "value" of `()` only on those
130 // paths in which we wish to convert `*self` to
131 // ambiguous (and return false, because the candidate
132 // was not used). On other paths, it is not assigned,
133 // and hence if those paths *could* reach the code that
134 // comes after the match, this fn would not compile.
135 let convert_to_ambiguous;
139 *self = Single(candidate);
144 // Duplicates can happen inside ParamEnv. In the case, we
145 // perform a lazy deduplication.
146 if current == &candidate {
150 // Prefer where-clauses. As in select, if there are multiple
151 // candidates, we prefer where-clause candidates over impls. This
152 // may seem a bit surprising, since impls are the source of
153 // "truth" in some sense, but in fact some of the impls that SEEM
154 // applicable are not, because of nested obligations. Where
155 // clauses are the safer choice. See the comment on
156 // `select::SelectionCandidate` and #21974 for more details.
157 match (current, candidate) {
158 (ParamEnv(..), ParamEnv(..)) => convert_to_ambiguous = (),
159 (ParamEnv(..), _) => return false,
160 (_, ParamEnv(..)) => unreachable!(),
161 (_, _) => convert_to_ambiguous = (),
165 Ambiguous | Error(..) => {
170 // We only ever get here when we moved from a single candidate
172 let () = convert_to_ambiguous;
178 /// Evaluates constraints of the form:
180 /// for<...> <T as Trait>::U == V
182 /// If successful, this may result in additional obligations. Also returns
183 /// the projection cache key used to track these additional obligations.
184 pub fn poly_project_and_unify_type<'cx, 'gcx, 'tcx>(
185 selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
186 obligation: &PolyProjectionObligation<'tcx>)
187 -> Result<Option<Vec<PredicateObligation<'tcx>>>,
188 MismatchedProjectionTypes<'tcx>>
190 debug!("poly_project_and_unify_type(obligation={:?})",
193 let infcx = selcx.infcx();
194 infcx.commit_if_ok(|snapshot| {
195 let (placeholder_predicate, placeholder_map) =
196 infcx.replace_bound_vars_with_placeholders(&obligation.predicate);
198 let placeholder_obligation = obligation.with(placeholder_predicate);
199 let result = project_and_unify_type(selcx, &placeholder_obligation)?;
200 infcx.leak_check(false, &placeholder_map, snapshot)
201 .map_err(|err| MismatchedProjectionTypes { err })?;
206 /// Evaluates constraints of the form:
208 /// <T as Trait>::U == V
210 /// If successful, this may result in additional obligations.
211 fn project_and_unify_type<'cx, 'gcx, 'tcx>(
212 selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
213 obligation: &ProjectionObligation<'tcx>)
214 -> Result<Option<Vec<PredicateObligation<'tcx>>>,
215 MismatchedProjectionTypes<'tcx>>
217 debug!("project_and_unify_type(obligation={:?})",
220 let mut obligations = vec![];
222 match opt_normalize_projection_type(selcx,
223 obligation.param_env,
224 obligation.predicate.projection_ty,
225 obligation.cause.clone(),
226 obligation.recursion_depth,
229 None => return Ok(None),
232 debug!("project_and_unify_type: normalized_ty={:?} obligations={:?}",
236 let infcx = selcx.infcx();
237 match infcx.at(&obligation.cause, obligation.param_env)
238 .eq(normalized_ty, obligation.predicate.ty) {
239 Ok(InferOk { obligations: inferred_obligations, value: () }) => {
240 obligations.extend(inferred_obligations);
241 Ok(Some(obligations))
244 debug!("project_and_unify_type: equating types encountered error {:?}", err);
245 Err(MismatchedProjectionTypes { err })
250 /// Normalizes any associated type projections in `value`, replacing
251 /// them with a fully resolved type where possible. The return value
252 /// combines the normalized result and any additional obligations that
253 /// were incurred as result.
254 pub fn normalize<'a, 'b, 'gcx, 'tcx, T>(selcx: &'a mut SelectionContext<'b, 'gcx, 'tcx>,
255 param_env: ty::ParamEnv<'tcx>,
256 cause: ObligationCause<'tcx>,
258 -> Normalized<'tcx, T>
259 where T : TypeFoldable<'tcx>
261 normalize_with_depth(selcx, param_env, cause, 0, value)
264 /// As `normalize`, but with a custom depth.
265 pub fn normalize_with_depth<'a, 'b, 'gcx, 'tcx, T>(
266 selcx: &'a mut SelectionContext<'b, 'gcx, 'tcx>,
267 param_env: ty::ParamEnv<'tcx>,
268 cause: ObligationCause<'tcx>,
271 -> Normalized<'tcx, T>
273 where T : TypeFoldable<'tcx>
275 debug!("normalize_with_depth(depth={}, value={:?})", depth, value);
276 let mut normalizer = AssociatedTypeNormalizer::new(selcx, param_env, cause, depth);
277 let result = normalizer.fold(value);
278 debug!("normalize_with_depth: depth={} result={:?} with {} obligations",
279 depth, result, normalizer.obligations.len());
280 debug!("normalize_with_depth: depth={} obligations={:?}",
281 depth, normalizer.obligations);
284 obligations: normalizer.obligations,
288 struct AssociatedTypeNormalizer<'a, 'b: 'a, 'gcx: 'b+'tcx, 'tcx: 'b> {
289 selcx: &'a mut SelectionContext<'b, 'gcx, 'tcx>,
290 param_env: ty::ParamEnv<'tcx>,
291 cause: ObligationCause<'tcx>,
292 obligations: Vec<PredicateObligation<'tcx>>,
296 impl<'a, 'b, 'gcx, 'tcx> AssociatedTypeNormalizer<'a, 'b, 'gcx, 'tcx> {
297 fn new(selcx: &'a mut SelectionContext<'b, 'gcx, 'tcx>,
298 param_env: ty::ParamEnv<'tcx>,
299 cause: ObligationCause<'tcx>,
301 -> AssociatedTypeNormalizer<'a, 'b, 'gcx, 'tcx>
303 AssociatedTypeNormalizer {
312 fn fold<T:TypeFoldable<'tcx>>(&mut self, value: &T) -> T {
313 let value = self.selcx.infcx().resolve_type_vars_if_possible(value);
315 if !value.has_projections() {
318 value.fold_with(self)
323 impl<'a, 'b, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for AssociatedTypeNormalizer<'a, 'b, 'gcx, 'tcx> {
324 fn tcx<'c>(&'c self) -> TyCtxt<'c, 'gcx, 'tcx> {
328 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
329 // We don't want to normalize associated types that occur inside of region
330 // binders, because they may contain bound regions, and we can't cope with that.
334 // for<'a> fn(<T as Foo<&'a>>::A)
336 // Instead of normalizing `<T as Foo<&'a>>::A` here, we'll
337 // normalize it when we instantiate those bound regions (which
338 // should occur eventually).
340 let ty = ty.super_fold_with(self);
342 ty::Opaque(def_id, substs) if !substs.has_escaping_bound_vars() => { // (*)
343 // Only normalize `impl Trait` after type-checking, usually in codegen.
344 match self.param_env.reveal {
345 Reveal::UserFacing => ty,
348 let recursion_limit = *self.tcx().sess.recursion_limit.get();
349 if self.depth >= recursion_limit {
350 let obligation = Obligation::with_depth(
356 self.selcx.infcx().report_overflow_error(&obligation, true);
359 let generic_ty = self.tcx().type_of(def_id);
360 let concrete_ty = generic_ty.subst(self.tcx(), substs);
362 let folded_ty = self.fold_ty(concrete_ty);
369 ty::Projection(ref data) if !data.has_escaping_bound_vars() => { // (*)
371 // (*) This is kind of hacky -- we need to be able to
372 // handle normalization within binders because
373 // otherwise we wind up a need to normalize when doing
374 // trait matching (since you can have a trait
375 // obligation like `for<'a> T::B : Fn(&'a int)`), but
376 // we can't normalize with bound regions in scope. So
377 // far now we just ignore binders but only normalize
378 // if all bound regions are gone (and then we still
379 // have to renormalize whenever we instantiate a
380 // binder). It would be better to normalize in a
381 // binding-aware fashion.
383 let normalized_ty = normalize_projection_type(self.selcx,
388 &mut self.obligations);
389 debug!("AssociatedTypeNormalizer: depth={} normalized {:?} to {:?}, \
390 now with {} obligations",
391 self.depth, ty, normalized_ty, self.obligations.len());
399 fn fold_const(&mut self, constant: &'tcx ty::LazyConst<'tcx>) -> &'tcx ty::LazyConst<'tcx> {
400 if let ty::LazyConst::Unevaluated(def_id, substs) = *constant {
401 let tcx = self.selcx.tcx().global_tcx();
402 if let Some(param_env) = self.tcx().lift_to_global(&self.param_env) {
403 if substs.needs_infer() || substs.has_placeholders() {
404 let identity_substs = Substs::identity_for_item(tcx, def_id);
405 let instance = ty::Instance::resolve(tcx, param_env, def_id, identity_substs);
406 if let Some(instance) = instance {
411 if let Ok(evaluated) = tcx.const_eval(param_env.and(cid)) {
412 let substs = tcx.lift_to_global(&substs).unwrap();
413 let evaluated = evaluated.subst(tcx, substs);
414 return tcx.mk_lazy_const(ty::LazyConst::Evaluated(evaluated));
418 if let Some(substs) = self.tcx().lift_to_global(&substs) {
419 let instance = ty::Instance::resolve(tcx, param_env, def_id, substs);
420 if let Some(instance) = instance {
425 if let Ok(evaluated) = tcx.const_eval(param_env.and(cid)) {
426 return tcx.mk_lazy_const(ty::LazyConst::Evaluated(evaluated));
438 pub struct Normalized<'tcx,T> {
440 pub obligations: Vec<PredicateObligation<'tcx>>,
443 pub type NormalizedTy<'tcx> = Normalized<'tcx, Ty<'tcx>>;
445 impl<'tcx,T> Normalized<'tcx,T> {
446 pub fn with<U>(self, value: U) -> Normalized<'tcx,U> {
447 Normalized { value: value, obligations: self.obligations }
451 /// The guts of `normalize`: normalize a specific projection like `<T
452 /// as Trait>::Item`. The result is always a type (and possibly
453 /// additional obligations). If ambiguity arises, which implies that
454 /// there are unresolved type variables in the projection, we will
455 /// substitute a fresh type variable `$X` and generate a new
456 /// obligation `<T as Trait>::Item == $X` for later.
457 pub fn normalize_projection_type<'a, 'b, 'gcx, 'tcx>(
458 selcx: &'a mut SelectionContext<'b, 'gcx, 'tcx>,
459 param_env: ty::ParamEnv<'tcx>,
460 projection_ty: ty::ProjectionTy<'tcx>,
461 cause: ObligationCause<'tcx>,
463 obligations: &mut Vec<PredicateObligation<'tcx>>)
466 opt_normalize_projection_type(selcx, param_env, projection_ty.clone(), cause.clone(), depth,
468 .unwrap_or_else(move || {
469 // if we bottom out in ambiguity, create a type variable
470 // and a deferred predicate to resolve this when more type
471 // information is available.
473 let tcx = selcx.infcx().tcx;
474 let def_id = projection_ty.item_def_id;
475 let ty_var = selcx.infcx().next_ty_var(
476 TypeVariableOrigin::NormalizeProjectionType(tcx.def_span(def_id)));
477 let projection = ty::Binder::dummy(ty::ProjectionPredicate {
481 let obligation = Obligation::with_depth(
482 cause, depth + 1, param_env, projection.to_predicate());
483 obligations.push(obligation);
488 /// The guts of `normalize`: normalize a specific projection like `<T
489 /// as Trait>::Item`. The result is always a type (and possibly
490 /// additional obligations). Returns `None` in the case of ambiguity,
491 /// which indicates that there are unbound type variables.
493 /// This function used to return `Option<NormalizedTy<'tcx>>`, which contains a
494 /// `Ty<'tcx>` and an obligations vector. But that obligation vector was very
495 /// often immediately appended to another obligations vector. So now this
496 /// function takes an obligations vector and appends to it directly, which is
497 /// slightly uglier but avoids the need for an extra short-lived allocation.
498 fn opt_normalize_projection_type<'a, 'b, 'gcx, 'tcx>(
499 selcx: &'a mut SelectionContext<'b, 'gcx, 'tcx>,
500 param_env: ty::ParamEnv<'tcx>,
501 projection_ty: ty::ProjectionTy<'tcx>,
502 cause: ObligationCause<'tcx>,
504 obligations: &mut Vec<PredicateObligation<'tcx>>)
507 let infcx = selcx.infcx();
509 let projection_ty = infcx.resolve_type_vars_if_possible(&projection_ty);
510 let cache_key = ProjectionCacheKey { ty: projection_ty };
512 debug!("opt_normalize_projection_type(\
513 projection_ty={:?}, \
518 // FIXME(#20304) For now, I am caching here, which is good, but it
519 // means we don't capture the type variables that are created in
520 // the case of ambiguity. Which means we may create a large stream
521 // of such variables. OTOH, if we move the caching up a level, we
522 // would not benefit from caching when proving `T: Trait<U=Foo>`
523 // bounds. It might be the case that we want two distinct caches,
524 // or else another kind of cache entry.
526 let cache_result = infcx.projection_cache.borrow_mut().try_start(cache_key);
529 Err(ProjectionCacheEntry::Ambiguous) => {
530 // If we found ambiguity the last time, that generally
531 // means we will continue to do so until some type in the
532 // key changes (and we know it hasn't, because we just
533 // fully resolved it). One exception though is closure
534 // types, which can transition from having a fixed kind to
535 // no kind with no visible change in the key.
537 // FIXME(#32286) refactor this so that closure type
539 debug!("opt_normalize_projection_type: \
540 found cache entry: ambiguous");
541 if !projection_ty.has_closure_types() {
545 Err(ProjectionCacheEntry::InProgress) => {
546 // If while normalized A::B, we are asked to normalize
547 // A::B, just return A::B itself. This is a conservative
548 // answer, in the sense that A::B *is* clearly equivalent
549 // to A::B, though there may be a better value we can
552 // Under lazy normalization, this can arise when
553 // bootstrapping. That is, imagine an environment with a
554 // where-clause like `A::B == u32`. Now, if we are asked
555 // to normalize `A::B`, we will want to check the
556 // where-clauses in scope. So we will try to unify `A::B`
557 // with `A::B`, which can trigger a recursive
558 // normalization. In that case, I think we will want this code:
561 // let ty = selcx.tcx().mk_projection(projection_ty.item_def_id,
562 // projection_ty.substs;
563 // return Some(NormalizedTy { value: v, obligations: vec![] });
566 debug!("opt_normalize_projection_type: \
567 found cache entry: in-progress");
569 // But for now, let's classify this as an overflow:
570 let recursion_limit = *selcx.tcx().sess.recursion_limit.get();
571 let obligation = Obligation::with_depth(cause,
575 selcx.infcx().report_overflow_error(&obligation, false);
577 Err(ProjectionCacheEntry::NormalizedTy(ty)) => {
578 // This is the hottest path in this function.
580 // If we find the value in the cache, then return it along
581 // with the obligations that went along with it. Note
582 // that, when using a fulfillment context, these
583 // obligations could in principle be ignored: they have
584 // already been registered when the cache entry was
585 // created (and hence the new ones will quickly be
586 // discarded as duplicated). But when doing trait
587 // evaluation this is not the case, and dropping the trait
588 // evaluations can causes ICEs (e.g., #43132).
589 debug!("opt_normalize_projection_type: \
590 found normalized ty `{:?}`",
593 // Once we have inferred everything we need to know, we
594 // can ignore the `obligations` from that point on.
595 if !infcx.any_unresolved_type_vars(&ty.value) {
596 infcx.projection_cache.borrow_mut().complete_normalized(cache_key, &ty);
597 // No need to extend `obligations`.
599 obligations.extend(ty.obligations);
602 obligations.push(get_paranoid_cache_value_obligation(infcx,
607 return Some(ty.value);
609 Err(ProjectionCacheEntry::Error) => {
610 debug!("opt_normalize_projection_type: \
612 let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth);
613 obligations.extend(result.obligations);
614 return Some(result.value)
618 let obligation = Obligation::with_depth(cause.clone(), depth, param_env, projection_ty);
619 match project_type(selcx, &obligation) {
620 Ok(ProjectedTy::Progress(Progress { ty: projected_ty,
621 obligations: mut projected_obligations })) => {
622 // if projection succeeded, then what we get out of this
623 // is also non-normalized (consider: it was derived from
624 // an impl, where-clause etc) and hence we must
627 debug!("opt_normalize_projection_type: \
630 projected_obligations={:?}",
633 projected_obligations);
635 let result = if projected_ty.has_projections() {
636 let mut normalizer = AssociatedTypeNormalizer::new(selcx,
640 let normalized_ty = normalizer.fold(&projected_ty);
642 debug!("opt_normalize_projection_type: \
643 normalized_ty={:?} depth={}",
647 projected_obligations.extend(normalizer.obligations);
649 value: normalized_ty,
650 obligations: projected_obligations,
655 obligations: projected_obligations,
659 let cache_value = prune_cache_value_obligations(infcx, &result);
660 infcx.projection_cache.borrow_mut().insert_ty(cache_key, cache_value);
661 obligations.extend(result.obligations);
664 Ok(ProjectedTy::NoProgress(projected_ty)) => {
665 debug!("opt_normalize_projection_type: \
666 projected_ty={:?} no progress",
668 let result = Normalized {
672 infcx.projection_cache.borrow_mut().insert_ty(cache_key, result.clone());
673 // No need to extend `obligations`.
676 Err(ProjectionTyError::TooManyCandidates) => {
677 debug!("opt_normalize_projection_type: \
678 too many candidates");
679 infcx.projection_cache.borrow_mut()
680 .ambiguous(cache_key);
683 Err(ProjectionTyError::TraitSelectionError(_)) => {
684 debug!("opt_normalize_projection_type: ERROR");
685 // if we got an error processing the `T as Trait` part,
686 // just return `ty::err` but add the obligation `T :
687 // Trait`, which when processed will cause the error to be
690 infcx.projection_cache.borrow_mut()
692 let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth);
693 obligations.extend(result.obligations);
699 /// If there are unresolved type variables, then we need to include
700 /// any subobligations that bind them, at least until those type
701 /// variables are fully resolved.
702 fn prune_cache_value_obligations<'a, 'gcx, 'tcx>(infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
703 result: &NormalizedTy<'tcx>)
704 -> NormalizedTy<'tcx> {
705 if !infcx.any_unresolved_type_vars(&result.value) {
706 return NormalizedTy { value: result.value, obligations: vec![] };
709 let mut obligations: Vec<_> =
712 .filter(|obligation| match obligation.predicate {
713 // We found a `T: Foo<X = U>` predicate, let's check
714 // if `U` references any unresolved type
715 // variables. In principle, we only care if this
716 // projection can help resolve any of the type
717 // variables found in `result.value` -- but we just
718 // check for any type variables here, for fear of
719 // indirect obligations (e.g., we project to `?0`,
720 // but we have `T: Foo<X = ?1>` and `?1: Bar<X =
722 ty::Predicate::Projection(ref data) =>
723 infcx.any_unresolved_type_vars(&data.ty()),
725 // We are only interested in `T: Foo<X = U>` predicates, whre
726 // `U` references one of `unresolved_type_vars`. =)
732 obligations.shrink_to_fit();
734 NormalizedTy { value: result.value, obligations }
737 /// Whenever we give back a cache result for a projection like `<T as
738 /// Trait>::Item ==> X`, we *always* include the obligation to prove
739 /// that `T: Trait` (we may also include some other obligations). This
740 /// may or may not be necessary -- in principle, all the obligations
741 /// that must be proven to show that `T: Trait` were also returned
742 /// when the cache was first populated. But there are some vague concerns,
743 /// and so we take the precautionary measure of including `T: Trait` in
746 /// Concern #1. The current setup is fragile. Perhaps someone could
747 /// have failed to prove the concerns from when the cache was
748 /// populated, but also not have used a snapshot, in which case the
749 /// cache could remain populated even though `T: Trait` has not been
750 /// shown. In this case, the "other code" is at fault -- when you
751 /// project something, you are supposed to either have a snapshot or
752 /// else prove all the resulting obligations -- but it's still easy to
755 /// Concern #2. Even within the snapshot, if those original
756 /// obligations are not yet proven, then we are able to do projections
757 /// that may yet turn out to be wrong. This *may* lead to some sort
758 /// of trouble, though we don't have a concrete example of how that
759 /// can occur yet. But it seems risky at best.
760 fn get_paranoid_cache_value_obligation<'a, 'gcx, 'tcx>(
761 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
762 param_env: ty::ParamEnv<'tcx>,
763 projection_ty: ty::ProjectionTy<'tcx>,
764 cause: ObligationCause<'tcx>,
766 -> PredicateObligation<'tcx>
768 let trait_ref = projection_ty.trait_ref(infcx.tcx).to_poly_trait_ref();
771 recursion_depth: depth,
773 predicate: trait_ref.to_predicate(),
777 /// If we are projecting `<T as Trait>::Item`, but `T: Trait` does not
778 /// hold. In various error cases, we cannot generate a valid
779 /// normalized projection. Therefore, we create an inference variable
780 /// return an associated obligation that, when fulfilled, will lead to
783 /// Note that we used to return `Error` here, but that was quite
784 /// dubious -- the premise was that an error would *eventually* be
785 /// reported, when the obligation was processed. But in general once
786 /// you see a `Error` you are supposed to be able to assume that an
787 /// error *has been* reported, so that you can take whatever heuristic
788 /// paths you want to take. To make things worse, it was possible for
789 /// cycles to arise, where you basically had a setup like `<MyType<$0>
790 /// as Trait>::Foo == $0`. Here, normalizing `<MyType<$0> as
791 /// Trait>::Foo> to `[type error]` would lead to an obligation of
792 /// `<MyType<[type error]> as Trait>::Foo`. We are supposed to report
793 /// an error for this obligation, but we legitimately should not,
794 /// because it contains `[type error]`. Yuck! (See issue #29857 for
795 /// one case where this arose.)
796 fn normalize_to_error<'a, 'gcx, 'tcx>(selcx: &mut SelectionContext<'a, 'gcx, 'tcx>,
797 param_env: ty::ParamEnv<'tcx>,
798 projection_ty: ty::ProjectionTy<'tcx>,
799 cause: ObligationCause<'tcx>,
801 -> NormalizedTy<'tcx>
803 let trait_ref = projection_ty.trait_ref(selcx.tcx()).to_poly_trait_ref();
804 let trait_obligation = Obligation { cause,
805 recursion_depth: depth,
807 predicate: trait_ref.to_predicate() };
808 let tcx = selcx.infcx().tcx;
809 let def_id = projection_ty.item_def_id;
810 let new_value = selcx.infcx().next_ty_var(
811 TypeVariableOrigin::NormalizeProjectionType(tcx.def_span(def_id)));
814 obligations: vec![trait_obligation]
818 enum ProjectedTy<'tcx> {
819 Progress(Progress<'tcx>),
820 NoProgress(Ty<'tcx>),
823 struct Progress<'tcx> {
825 obligations: Vec<PredicateObligation<'tcx>>,
828 impl<'tcx> Progress<'tcx> {
829 fn error<'a,'gcx>(tcx: TyCtxt<'a,'gcx,'tcx>) -> Self {
836 fn with_addl_obligations(mut self,
837 mut obligations: Vec<PredicateObligation<'tcx>>)
839 debug!("with_addl_obligations: self.obligations.len={} obligations.len={}",
840 self.obligations.len(), obligations.len());
842 debug!("with_addl_obligations: self.obligations={:?} obligations={:?}",
843 self.obligations, obligations);
845 self.obligations.append(&mut obligations);
850 /// Computes the result of a projection type (if we can).
853 /// - `obligation` must be fully normalized
854 fn project_type<'cx, 'gcx, 'tcx>(
855 selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
856 obligation: &ProjectionTyObligation<'tcx>)
857 -> Result<ProjectedTy<'tcx>, ProjectionTyError<'tcx>>
859 debug!("project(obligation={:?})",
862 let recursion_limit = *selcx.tcx().sess.recursion_limit.get();
863 if obligation.recursion_depth >= recursion_limit {
864 debug!("project: overflow!");
865 return Err(ProjectionTyError::TraitSelectionError(SelectionError::Overflow));
868 let obligation_trait_ref = &obligation.predicate.trait_ref(selcx.tcx());
870 debug!("project: obligation_trait_ref={:?}", obligation_trait_ref);
872 if obligation_trait_ref.references_error() {
873 return Ok(ProjectedTy::Progress(Progress::error(selcx.tcx())));
876 let mut candidates = ProjectionTyCandidateSet::None;
878 // Make sure that the following procedures are kept in order. ParamEnv
879 // needs to be first because it has highest priority, and Select checks
880 // the return value of push_candidate which assumes it's ran at last.
881 assemble_candidates_from_param_env(selcx,
883 &obligation_trait_ref,
886 assemble_candidates_from_trait_def(selcx,
888 &obligation_trait_ref,
891 assemble_candidates_from_impls(selcx,
893 &obligation_trait_ref,
897 ProjectionTyCandidateSet::Single(candidate) => Ok(ProjectedTy::Progress(
898 confirm_candidate(selcx,
900 &obligation_trait_ref,
902 ProjectionTyCandidateSet::None => Ok(ProjectedTy::NoProgress(
903 selcx.tcx().mk_projection(
904 obligation.predicate.item_def_id,
905 obligation.predicate.substs))),
906 // Error occurred while trying to processing impls.
907 ProjectionTyCandidateSet::Error(e) => Err(ProjectionTyError::TraitSelectionError(e)),
908 // Inherent ambiguity that prevents us from even enumerating the
910 ProjectionTyCandidateSet::Ambiguous => Err(ProjectionTyError::TooManyCandidates),
915 /// The first thing we have to do is scan through the parameter
916 /// environment to see whether there are any projection predicates
917 /// there that can answer this question.
918 fn assemble_candidates_from_param_env<'cx, 'gcx, 'tcx>(
919 selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
920 obligation: &ProjectionTyObligation<'tcx>,
921 obligation_trait_ref: &ty::TraitRef<'tcx>,
922 candidate_set: &mut ProjectionTyCandidateSet<'tcx>)
924 debug!("assemble_candidates_from_param_env(..)");
925 assemble_candidates_from_predicates(selcx,
927 obligation_trait_ref,
929 ProjectionTyCandidate::ParamEnv,
930 obligation.param_env.caller_bounds.iter().cloned());
933 /// In the case of a nested projection like <<A as Foo>::FooT as Bar>::BarT, we may find
934 /// that the definition of `Foo` has some clues:
938 /// type FooT : Bar<BarT=i32>
942 /// Here, for example, we could conclude that the result is `i32`.
943 fn assemble_candidates_from_trait_def<'cx, 'gcx, 'tcx>(
944 selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
945 obligation: &ProjectionTyObligation<'tcx>,
946 obligation_trait_ref: &ty::TraitRef<'tcx>,
947 candidate_set: &mut ProjectionTyCandidateSet<'tcx>)
949 debug!("assemble_candidates_from_trait_def(..)");
951 let tcx = selcx.tcx();
952 // Check whether the self-type is itself a projection.
953 let (def_id, substs) = match obligation_trait_ref.self_ty().sty {
954 ty::Projection(ref data) => {
955 (data.trait_ref(tcx).def_id, data.substs)
957 ty::Opaque(def_id, substs) => (def_id, substs),
958 ty::Infer(ty::TyVar(_)) => {
959 // If the self-type is an inference variable, then it MAY wind up
960 // being a projected type, so induce an ambiguity.
961 candidate_set.mark_ambiguous();
967 // If so, extract what we know from the trait and try to come up with a good answer.
968 let trait_predicates = tcx.predicates_of(def_id);
969 let bounds = trait_predicates.instantiate(tcx, substs);
970 let bounds = elaborate_predicates(tcx, bounds.predicates);
971 assemble_candidates_from_predicates(selcx,
973 obligation_trait_ref,
975 ProjectionTyCandidate::TraitDef,
979 fn assemble_candidates_from_predicates<'cx, 'gcx, 'tcx, I>(
980 selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
981 obligation: &ProjectionTyObligation<'tcx>,
982 obligation_trait_ref: &ty::TraitRef<'tcx>,
983 candidate_set: &mut ProjectionTyCandidateSet<'tcx>,
984 ctor: fn(ty::PolyProjectionPredicate<'tcx>) -> ProjectionTyCandidate<'tcx>,
986 where I: IntoIterator<Item=ty::Predicate<'tcx>>
988 debug!("assemble_candidates_from_predicates(obligation={:?})",
990 let infcx = selcx.infcx();
991 for predicate in env_predicates {
992 debug!("assemble_candidates_from_predicates: predicate={:?}",
994 if let ty::Predicate::Projection(data) = predicate {
995 let same_def_id = data.projection_def_id() == obligation.predicate.item_def_id;
997 let is_match = same_def_id && infcx.probe(|_| {
998 let data_poly_trait_ref =
999 data.to_poly_trait_ref(infcx.tcx);
1000 let obligation_poly_trait_ref =
1001 obligation_trait_ref.to_poly_trait_ref();
1002 infcx.at(&obligation.cause, obligation.param_env)
1003 .sup(obligation_poly_trait_ref, data_poly_trait_ref)
1004 .map(|InferOk { obligations: _, value: () }| {
1005 // FIXME(#32730) -- do we need to take obligations
1006 // into account in any way? At the moment, no.
1011 debug!("assemble_candidates_from_predicates: candidate={:?} \
1012 is_match={} same_def_id={}",
1013 data, is_match, same_def_id);
1016 candidate_set.push_candidate(ctor(data));
1022 fn assemble_candidates_from_impls<'cx, 'gcx, 'tcx>(
1023 selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
1024 obligation: &ProjectionTyObligation<'tcx>,
1025 obligation_trait_ref: &ty::TraitRef<'tcx>,
1026 candidate_set: &mut ProjectionTyCandidateSet<'tcx>)
1028 // If we are resolving `<T as TraitRef<...>>::Item == Type`,
1029 // start out by selecting the predicate `T as TraitRef<...>`:
1030 let poly_trait_ref = obligation_trait_ref.to_poly_trait_ref();
1031 let trait_obligation = obligation.with(poly_trait_ref.to_poly_trait_predicate());
1032 let _ = selcx.infcx().commit_if_ok(|_| {
1033 let vtable = match selcx.select(&trait_obligation) {
1034 Ok(Some(vtable)) => vtable,
1036 candidate_set.mark_ambiguous();
1040 debug!("assemble_candidates_from_impls: selection error {:?}", e);
1041 candidate_set.mark_error(e);
1046 let eligible = match &vtable {
1047 super::VtableClosure(_) |
1048 super::VtableGenerator(_) |
1049 super::VtableFnPointer(_) |
1050 super::VtableObject(_) |
1051 super::VtableTraitAlias(_) => {
1052 debug!("assemble_candidates_from_impls: vtable={:?}",
1056 super::VtableImpl(impl_data) => {
1057 // We have to be careful when projecting out of an
1058 // impl because of specialization. If we are not in
1059 // codegen (i.e., projection mode is not "any"), and the
1060 // impl's type is declared as default, then we disable
1061 // projection (even if the trait ref is fully
1062 // monomorphic). In the case where trait ref is not
1063 // fully monomorphic (i.e., includes type parameters),
1064 // this is because those type parameters may
1065 // ultimately be bound to types from other crates that
1066 // may have specialized impls we can't see. In the
1067 // case where the trait ref IS fully monomorphic, this
1068 // is a policy decision that we made in the RFC in
1069 // order to preserve flexibility for the crate that
1070 // defined the specializable impl to specialize later
1071 // for existing types.
1073 // In either case, we handle this by not adding a
1074 // candidate for an impl if it contains a `default`
1076 let node_item = assoc_ty_def(selcx,
1077 impl_data.impl_def_id,
1078 obligation.predicate.item_def_id);
1080 let is_default = if node_item.node.is_from_trait() {
1081 // If true, the impl inherited a `type Foo = Bar`
1082 // given in the trait, which is implicitly default.
1083 // Otherwise, the impl did not specify `type` and
1084 // neither did the trait:
1087 // trait Foo { type T; }
1088 // impl Foo for Bar { }
1091 // This is an error, but it will be
1092 // reported in `check_impl_items_against_trait`.
1093 // We accept it here but will flag it as
1094 // an error when we confirm the candidate
1095 // (which will ultimately lead to `normalize_to_error`
1097 node_item.item.defaultness.has_value()
1099 node_item.item.defaultness.is_default() ||
1100 selcx.tcx().impl_is_default(node_item.node.def_id())
1103 // Only reveal a specializable default if we're past type-checking
1104 // and the obligations is monomorphic, otherwise passes such as
1105 // transmute checking and polymorphic MIR optimizations could
1106 // get a result which isn't correct for all monomorphizations.
1109 } else if obligation.param_env.reveal == Reveal::All {
1110 debug_assert!(!poly_trait_ref.needs_infer());
1111 if !poly_trait_ref.needs_subst() {
1120 super::VtableParam(..) => {
1121 // This case tell us nothing about the value of an
1122 // associated type. Consider:
1125 // trait SomeTrait { type Foo; }
1126 // fn foo<T:SomeTrait>(...) { }
1129 // If the user writes `<T as SomeTrait>::Foo`, then the `T
1130 // : SomeTrait` binding does not help us decide what the
1131 // type `Foo` is (at least, not more specifically than
1132 // what we already knew).
1134 // But wait, you say! What about an example like this:
1137 // fn bar<T:SomeTrait<Foo=usize>>(...) { ... }
1140 // Doesn't the `T : Sometrait<Foo=usize>` predicate help
1141 // resolve `T::Foo`? And of course it does, but in fact
1142 // that single predicate is desugared into two predicates
1143 // in the compiler: a trait predicate (`T : SomeTrait`) and a
1144 // projection. And the projection where clause is handled
1145 // in `assemble_candidates_from_param_env`.
1148 super::VtableAutoImpl(..) |
1149 super::VtableBuiltin(..) => {
1150 // These traits have no associated types.
1152 obligation.cause.span,
1153 "Cannot project an associated type from `{:?}`",
1159 if candidate_set.push_candidate(ProjectionTyCandidate::Select(vtable)) {
1170 fn confirm_candidate<'cx, 'gcx, 'tcx>(
1171 selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
1172 obligation: &ProjectionTyObligation<'tcx>,
1173 obligation_trait_ref: &ty::TraitRef<'tcx>,
1174 candidate: ProjectionTyCandidate<'tcx>)
1177 debug!("confirm_candidate(candidate={:?}, obligation={:?})",
1182 ProjectionTyCandidate::ParamEnv(poly_projection) |
1183 ProjectionTyCandidate::TraitDef(poly_projection) => {
1184 confirm_param_env_candidate(selcx, obligation, poly_projection)
1187 ProjectionTyCandidate::Select(vtable) => {
1188 confirm_select_candidate(selcx, obligation, obligation_trait_ref, vtable)
1193 fn confirm_select_candidate<'cx, 'gcx, 'tcx>(
1194 selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
1195 obligation: &ProjectionTyObligation<'tcx>,
1196 obligation_trait_ref: &ty::TraitRef<'tcx>,
1197 vtable: Selection<'tcx>)
1201 super::VtableImpl(data) =>
1202 confirm_impl_candidate(selcx, obligation, data),
1203 super::VtableGenerator(data) =>
1204 confirm_generator_candidate(selcx, obligation, data),
1205 super::VtableClosure(data) =>
1206 confirm_closure_candidate(selcx, obligation, data),
1207 super::VtableFnPointer(data) =>
1208 confirm_fn_pointer_candidate(selcx, obligation, data),
1209 super::VtableObject(_) =>
1210 confirm_object_candidate(selcx, obligation, obligation_trait_ref),
1211 super::VtableAutoImpl(..) |
1212 super::VtableParam(..) |
1213 super::VtableBuiltin(..) |
1214 super::VtableTraitAlias(..) =>
1215 // we don't create Select candidates with this kind of resolution
1217 obligation.cause.span,
1218 "Cannot project an associated type from `{:?}`",
1223 fn confirm_object_candidate<'cx, 'gcx, 'tcx>(
1224 selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
1225 obligation: &ProjectionTyObligation<'tcx>,
1226 obligation_trait_ref: &ty::TraitRef<'tcx>)
1229 let self_ty = obligation_trait_ref.self_ty();
1230 let object_ty = selcx.infcx().shallow_resolve(self_ty);
1231 debug!("confirm_object_candidate(object_ty={:?})",
1233 let data = match object_ty.sty {
1234 ty::Dynamic(ref data, ..) => data,
1237 obligation.cause.span,
1238 "confirm_object_candidate called with non-object: {:?}",
1242 let env_predicates = data.projection_bounds().map(|p| {
1243 p.with_self_ty(selcx.tcx(), object_ty).to_predicate()
1245 let env_predicate = {
1246 let env_predicates = elaborate_predicates(selcx.tcx(), env_predicates);
1248 // select only those projections that are actually projecting an
1249 // item with the correct name
1250 let env_predicates = env_predicates.filter_map(|p| match p {
1251 ty::Predicate::Projection(data) =>
1252 if data.projection_def_id() == obligation.predicate.item_def_id {
1260 // select those with a relevant trait-ref
1261 let mut env_predicates = env_predicates.filter(|data| {
1262 let data_poly_trait_ref = data.to_poly_trait_ref(selcx.tcx());
1263 let obligation_poly_trait_ref = obligation_trait_ref.to_poly_trait_ref();
1264 selcx.infcx().probe(|_|
1265 selcx.infcx().at(&obligation.cause, obligation.param_env)
1266 .sup(obligation_poly_trait_ref, data_poly_trait_ref)
1271 // select the first matching one; there really ought to be one or
1272 // else the object type is not WF, since an object type should
1273 // include all of its projections explicitly
1274 match env_predicates.next() {
1275 Some(env_predicate) => env_predicate,
1277 debug!("confirm_object_candidate: no env-predicate \
1278 found in object type `{:?}`; ill-formed",
1280 return Progress::error(selcx.tcx());
1285 confirm_param_env_candidate(selcx, obligation, env_predicate)
1288 fn confirm_generator_candidate<'cx, 'gcx, 'tcx>(
1289 selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
1290 obligation: &ProjectionTyObligation<'tcx>,
1291 vtable: VtableGeneratorData<'tcx, PredicateObligation<'tcx>>)
1294 let gen_sig = vtable.substs.poly_sig(vtable.generator_def_id, selcx.tcx());
1298 } = normalize_with_depth(selcx,
1299 obligation.param_env,
1300 obligation.cause.clone(),
1301 obligation.recursion_depth+1,
1304 debug!("confirm_generator_candidate: obligation={:?},gen_sig={:?},obligations={:?}",
1309 let tcx = selcx.tcx();
1311 let gen_def_id = tcx.lang_items().gen_trait().unwrap();
1314 tcx.generator_trait_ref_and_outputs(gen_def_id,
1315 obligation.predicate.self_ty(),
1317 .map_bound(|(trait_ref, yield_ty, return_ty)| {
1318 let name = tcx.associated_item(obligation.predicate.item_def_id).ident.name;
1319 let ty = if name == "Return" {
1321 } else if name == "Yield" {
1327 ty::ProjectionPredicate {
1328 projection_ty: ty::ProjectionTy {
1329 substs: trait_ref.substs,
1330 item_def_id: obligation.predicate.item_def_id,
1336 confirm_param_env_candidate(selcx, obligation, predicate)
1337 .with_addl_obligations(vtable.nested)
1338 .with_addl_obligations(obligations)
1341 fn confirm_fn_pointer_candidate<'cx, 'gcx, 'tcx>(
1342 selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
1343 obligation: &ProjectionTyObligation<'tcx>,
1344 fn_pointer_vtable: VtableFnPointerData<'tcx, PredicateObligation<'tcx>>)
1347 let fn_type = selcx.infcx().shallow_resolve(fn_pointer_vtable.fn_ty);
1348 let sig = fn_type.fn_sig(selcx.tcx());
1352 } = normalize_with_depth(selcx,
1353 obligation.param_env,
1354 obligation.cause.clone(),
1355 obligation.recursion_depth+1,
1358 confirm_callable_candidate(selcx, obligation, sig, util::TupleArgumentsFlag::Yes)
1359 .with_addl_obligations(fn_pointer_vtable.nested)
1360 .with_addl_obligations(obligations)
1363 fn confirm_closure_candidate<'cx, 'gcx, 'tcx>(
1364 selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
1365 obligation: &ProjectionTyObligation<'tcx>,
1366 vtable: VtableClosureData<'tcx, PredicateObligation<'tcx>>)
1369 let tcx = selcx.tcx();
1370 let infcx = selcx.infcx();
1371 let closure_sig_ty = vtable.substs.closure_sig_ty(vtable.closure_def_id, tcx);
1372 let closure_sig = infcx.shallow_resolve(&closure_sig_ty).fn_sig(tcx);
1376 } = normalize_with_depth(selcx,
1377 obligation.param_env,
1378 obligation.cause.clone(),
1379 obligation.recursion_depth+1,
1382 debug!("confirm_closure_candidate: obligation={:?},closure_sig={:?},obligations={:?}",
1387 confirm_callable_candidate(selcx,
1390 util::TupleArgumentsFlag::No)
1391 .with_addl_obligations(vtable.nested)
1392 .with_addl_obligations(obligations)
1395 fn confirm_callable_candidate<'cx, 'gcx, 'tcx>(
1396 selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
1397 obligation: &ProjectionTyObligation<'tcx>,
1398 fn_sig: ty::PolyFnSig<'tcx>,
1399 flag: util::TupleArgumentsFlag)
1402 let tcx = selcx.tcx();
1404 debug!("confirm_callable_candidate({:?},{:?})",
1408 // the `Output` associated type is declared on `FnOnce`
1409 let fn_once_def_id = tcx.lang_items().fn_once_trait().unwrap();
1412 tcx.closure_trait_ref_and_return_type(fn_once_def_id,
1413 obligation.predicate.self_ty(),
1416 .map_bound(|(trait_ref, ret_type)|
1417 ty::ProjectionPredicate {
1418 projection_ty: ty::ProjectionTy::from_ref_and_name(
1421 Ident::from_str(FN_OUTPUT_NAME),
1427 confirm_param_env_candidate(selcx, obligation, predicate)
1430 fn confirm_param_env_candidate<'cx, 'gcx, 'tcx>(
1431 selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
1432 obligation: &ProjectionTyObligation<'tcx>,
1433 poly_cache_entry: ty::PolyProjectionPredicate<'tcx>,
1434 ) -> Progress<'tcx> {
1435 let infcx = selcx.infcx();
1436 let cause = &obligation.cause;
1437 let param_env = obligation.param_env;
1439 let (cache_entry, _) =
1440 infcx.replace_bound_vars_with_fresh_vars(
1442 LateBoundRegionConversionTime::HigherRankedType,
1445 let cache_trait_ref = cache_entry.projection_ty.trait_ref(infcx.tcx);
1446 let obligation_trait_ref = obligation.predicate.trait_ref(infcx.tcx);
1447 match infcx.at(cause, param_env).eq(cache_trait_ref, obligation_trait_ref) {
1448 Ok(InferOk { value: _, obligations }) => {
1456 obligation.cause.span,
1457 "Failed to unify obligation `{:?}` \
1458 with poly_projection `{:?}`: {:?}",
1466 fn confirm_impl_candidate<'cx, 'gcx, 'tcx>(
1467 selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
1468 obligation: &ProjectionTyObligation<'tcx>,
1469 impl_vtable: VtableImplData<'tcx, PredicateObligation<'tcx>>)
1472 let VtableImplData { impl_def_id, substs, nested } = impl_vtable;
1474 let tcx = selcx.tcx();
1475 let param_env = obligation.param_env;
1476 let assoc_ty = assoc_ty_def(selcx, impl_def_id, obligation.predicate.item_def_id);
1478 if !assoc_ty.item.defaultness.has_value() {
1479 // This means that the impl is missing a definition for the
1480 // associated type. This error will be reported by the type
1481 // checker method `check_impl_items_against_trait`, so here we
1482 // just return Error.
1483 debug!("confirm_impl_candidate: no associated type {:?} for {:?}",
1484 assoc_ty.item.ident,
1485 obligation.predicate);
1488 obligations: nested,
1491 let substs = translate_substs(selcx.infcx(), param_env, impl_def_id, substs, assoc_ty.node);
1492 let ty = if let ty::AssociatedKind::Existential = assoc_ty.item.kind {
1493 let item_substs = Substs::identity_for_item(tcx, assoc_ty.item.def_id);
1494 tcx.mk_opaque(assoc_ty.item.def_id, item_substs)
1496 tcx.type_of(assoc_ty.item.def_id)
1499 ty: ty.subst(tcx, substs),
1500 obligations: nested,
1504 /// Locate the definition of an associated type in the specialization hierarchy,
1505 /// starting from the given impl.
1507 /// Based on the "projection mode", this lookup may in fact only examine the
1508 /// topmost impl. See the comments for `Reveal` for more details.
1509 fn assoc_ty_def<'cx, 'gcx, 'tcx>(
1510 selcx: &SelectionContext<'cx, 'gcx, 'tcx>,
1512 assoc_ty_def_id: DefId)
1513 -> specialization_graph::NodeItem<ty::AssociatedItem>
1515 let tcx = selcx.tcx();
1516 let assoc_ty_name = tcx.associated_item(assoc_ty_def_id).ident;
1517 let trait_def_id = tcx.impl_trait_ref(impl_def_id).unwrap().def_id;
1518 let trait_def = tcx.trait_def(trait_def_id);
1520 // This function may be called while we are still building the
1521 // specialization graph that is queried below (via TraidDef::ancestors()),
1522 // so, in order to avoid unnecessary infinite recursion, we manually look
1523 // for the associated item at the given impl.
1524 // If there is no such item in that impl, this function will fail with a
1525 // cycle error if the specialization graph is currently being built.
1526 let impl_node = specialization_graph::Node::Impl(impl_def_id);
1527 for item in impl_node.items(tcx) {
1528 if item.kind == ty::AssociatedKind::Type &&
1529 tcx.hygienic_eq(item.ident, assoc_ty_name, trait_def_id) {
1530 return specialization_graph::NodeItem {
1531 node: specialization_graph::Node::Impl(impl_def_id),
1537 if let Some(assoc_item) = trait_def
1538 .ancestors(tcx, impl_def_id)
1539 .defs(tcx, assoc_ty_name, ty::AssociatedKind::Type, trait_def_id)
1543 // This is saying that neither the trait nor
1544 // the impl contain a definition for this
1545 // associated type. Normally this situation
1546 // could only arise through a compiler bug --
1547 // if the user wrote a bad item name, it
1548 // should have failed in astconv.
1549 bug!("No associated type `{}` for {}",
1551 tcx.item_path_str(impl_def_id))
1557 /// The projection cache. Unlike the standard caches, this can include
1558 /// infcx-dependent type variables, therefore we have to roll the
1559 /// cache back each time we roll a snapshot back, to avoid assumptions
1560 /// on yet-unresolved inference variables. Types with placeholder
1561 /// regions also have to be removed when the respective snapshot ends.
1563 /// Because of that, projection cache entries can be "stranded" and left
1564 /// inaccessible when type variables inside the key are resolved. We make no
1565 /// attempt to recover or remove "stranded" entries, but rather let them be
1566 /// (for the lifetime of the infcx).
1568 /// Entries in the projection cache might contain inference variables
1569 /// that will be resolved by obligations on the projection cache entry (e.g.,
1570 /// when a type parameter in the associated type is constrained through
1571 /// an "RFC 447" projection on the impl).
1573 /// When working with a fulfillment context, the derived obligations of each
1574 /// projection cache entry will be registered on the fulfillcx, so any users
1575 /// that can wait for a fulfillcx fixed point need not care about this. However,
1576 /// users that don't wait for a fixed point (e.g., trait evaluation) have to
1577 /// resolve the obligations themselves to make sure the projected result is
1578 /// ok and avoid issues like #43132.
1580 /// If that is done, after evaluation the obligations, it is a good idea to
1581 /// call `ProjectionCache::complete` to make sure the obligations won't be
1582 /// re-evaluated and avoid an exponential worst-case.
1584 // FIXME: we probably also want some sort of cross-infcx cache here to
1585 // reduce the amount of duplication. Let's see what we get with the Chalk reforms.
1587 pub struct ProjectionCache<'tcx> {
1588 map: SnapshotMap<ProjectionCacheKey<'tcx>, ProjectionCacheEntry<'tcx>>,
1591 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
1592 pub struct ProjectionCacheKey<'tcx> {
1593 ty: ty::ProjectionTy<'tcx>
1596 impl<'cx, 'gcx, 'tcx> ProjectionCacheKey<'tcx> {
1597 pub fn from_poly_projection_predicate(selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
1598 predicate: &ty::PolyProjectionPredicate<'tcx>)
1601 let infcx = selcx.infcx();
1602 // We don't do cross-snapshot caching of obligations with escaping regions,
1603 // so there's no cache key to use
1604 predicate.no_bound_vars()
1605 .map(|predicate| ProjectionCacheKey {
1606 // We don't attempt to match up with a specific type-variable state
1607 // from a specific call to `opt_normalize_projection_type` - if
1608 // there's no precise match, the original cache entry is "stranded"
1610 ty: infcx.resolve_type_vars_if_possible(&predicate.projection_ty)
1615 #[derive(Clone, Debug)]
1616 enum ProjectionCacheEntry<'tcx> {
1620 NormalizedTy(NormalizedTy<'tcx>),
1623 // N.B., intentionally not Clone
1624 pub struct ProjectionCacheSnapshot {
1628 impl<'tcx> ProjectionCache<'tcx> {
1629 pub fn clear(&mut self) {
1633 pub fn snapshot(&mut self) -> ProjectionCacheSnapshot {
1634 ProjectionCacheSnapshot { snapshot: self.map.snapshot() }
1637 pub fn rollback_to(&mut self, snapshot: ProjectionCacheSnapshot) {
1638 self.map.rollback_to(snapshot.snapshot);
1641 pub fn rollback_placeholder(&mut self, snapshot: &ProjectionCacheSnapshot) {
1642 self.map.partial_rollback(&snapshot.snapshot, &|k| k.ty.has_re_placeholders());
1645 pub fn commit(&mut self, snapshot: ProjectionCacheSnapshot) {
1646 self.map.commit(snapshot.snapshot);
1649 /// Try to start normalize `key`; returns an error if
1650 /// normalization already occurred (this error corresponds to a
1651 /// cache hit, so it's actually a good thing).
1652 fn try_start(&mut self, key: ProjectionCacheKey<'tcx>)
1653 -> Result<(), ProjectionCacheEntry<'tcx>> {
1654 if let Some(entry) = self.map.get(&key) {
1655 return Err(entry.clone());
1658 self.map.insert(key, ProjectionCacheEntry::InProgress);
1662 /// Indicates that `key` was normalized to `value`.
1663 fn insert_ty(&mut self, key: ProjectionCacheKey<'tcx>, value: NormalizedTy<'tcx>) {
1664 debug!("ProjectionCacheEntry::insert_ty: adding cache entry: key={:?}, value={:?}",
1666 let fresh_key = self.map.insert(key, ProjectionCacheEntry::NormalizedTy(value));
1667 assert!(!fresh_key, "never started projecting `{:?}`", key);
1670 /// Mark the relevant projection cache key as having its derived obligations
1671 /// complete, so they won't have to be re-computed (this is OK to do in a
1672 /// snapshot - if the snapshot is rolled back, the obligations will be
1673 /// marked as incomplete again).
1674 pub fn complete(&mut self, key: ProjectionCacheKey<'tcx>) {
1675 let ty = match self.map.get(&key) {
1676 Some(&ProjectionCacheEntry::NormalizedTy(ref ty)) => {
1677 debug!("ProjectionCacheEntry::complete({:?}) - completing {:?}",
1682 // Type inference could "strand behind" old cache entries. Leave
1683 // them alone for now.
1684 debug!("ProjectionCacheEntry::complete({:?}) - ignoring {:?}",
1690 self.map.insert(key, ProjectionCacheEntry::NormalizedTy(Normalized {
1696 /// A specialized version of `complete` for when the key's value is known
1697 /// to be a NormalizedTy.
1698 pub fn complete_normalized(&mut self, key: ProjectionCacheKey<'tcx>, ty: &NormalizedTy<'tcx>) {
1699 // We want to insert `ty` with no obligations. If the existing value
1700 // already has no obligations (as is common) we don't insert anything.
1701 if !ty.obligations.is_empty() {
1702 self.map.insert(key, ProjectionCacheEntry::NormalizedTy(Normalized {
1709 /// Indicates that trying to normalize `key` resulted in
1710 /// ambiguity. No point in trying it again then until we gain more
1711 /// type information (in which case, the "fully resolved" key will
1713 fn ambiguous(&mut self, key: ProjectionCacheKey<'tcx>) {
1714 let fresh = self.map.insert(key, ProjectionCacheEntry::Ambiguous);
1715 assert!(!fresh, "never started projecting `{:?}`", key);
1718 /// Indicates that trying to normalize `key` resulted in
1720 fn error(&mut self, key: ProjectionCacheKey<'tcx>) {
1721 let fresh = self.map.insert(key, ProjectionCacheEntry::Error);
1722 assert!(!fresh, "never started projecting `{:?}`", key);