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;
8 use super::ObligationCause;
9 use super::PredicateObligation;
11 use super::SelectionContext;
12 use super::SelectionError;
13 use super::{VtableClosureData, VtableFnPointerData, VtableGeneratorData, VtableImplData};
15 use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
16 use crate::infer::{InferCtxt, InferOk, LateBoundRegionConversionTime};
17 use rustc::ty::fold::{TypeFoldable, TypeFolder};
18 use rustc::ty::subst::{InternalSubsts, Subst};
19 use rustc::ty::{self, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, WithConstness};
20 use rustc_ast::ast::Ident;
21 use rustc_data_structures::snapshot_map::{Snapshot, SnapshotMap};
22 use rustc_hir::def_id::DefId;
23 use rustc_span::symbol::sym;
24 use rustc_span::DUMMY_SP;
26 pub use rustc::traits::Reveal;
28 pub type PolyProjectionObligation<'tcx> = Obligation<'tcx, ty::PolyProjectionPredicate<'tcx>>;
30 pub type ProjectionObligation<'tcx> = Obligation<'tcx, ty::ProjectionPredicate<'tcx>>;
32 pub type ProjectionTyObligation<'tcx> = Obligation<'tcx, ty::ProjectionTy<'tcx>>;
34 /// When attempting to resolve `<T as TraitRef>::Name` ...
36 pub enum ProjectionTyError<'tcx> {
37 /// ...we found multiple sources of information and couldn't resolve the ambiguity.
40 /// ...an error occurred matching `T : TraitRef`
41 TraitSelectionError(SelectionError<'tcx>),
45 pub struct MismatchedProjectionTypes<'tcx> {
46 pub err: ty::error::TypeError<'tcx>,
49 #[derive(PartialEq, Eq, Debug)]
50 enum ProjectionTyCandidate<'tcx> {
51 // from a where-clause in the env or object type
52 ParamEnv(ty::PolyProjectionPredicate<'tcx>),
54 // from the definition of `Trait` when you have something like <<A as Trait>::B as Trait2>::C
55 TraitDef(ty::PolyProjectionPredicate<'tcx>),
57 // from a "impl" (or a "pseudo-impl" returned by select)
58 Select(Selection<'tcx>),
61 enum ProjectionTyCandidateSet<'tcx> {
63 Single(ProjectionTyCandidate<'tcx>),
65 Error(SelectionError<'tcx>),
68 impl<'tcx> ProjectionTyCandidateSet<'tcx> {
69 fn mark_ambiguous(&mut self) {
70 *self = ProjectionTyCandidateSet::Ambiguous;
73 fn mark_error(&mut self, err: SelectionError<'tcx>) {
74 *self = ProjectionTyCandidateSet::Error(err);
77 // Returns true if the push was successful, or false if the candidate
78 // was discarded -- this could be because of ambiguity, or because
79 // a higher-priority candidate is already there.
80 fn push_candidate(&mut self, candidate: ProjectionTyCandidate<'tcx>) -> bool {
81 use self::ProjectionTyCandidate::*;
82 use self::ProjectionTyCandidateSet::*;
84 // This wacky variable is just used to try and
85 // make code readable and avoid confusing paths.
86 // It is assigned a "value" of `()` only on those
87 // paths in which we wish to convert `*self` to
88 // ambiguous (and return false, because the candidate
89 // was not used). On other paths, it is not assigned,
90 // and hence if those paths *could* reach the code that
91 // comes after the match, this fn would not compile.
92 let convert_to_ambiguous;
96 *self = Single(candidate);
101 // Duplicates can happen inside ParamEnv. In the case, we
102 // perform a lazy deduplication.
103 if current == &candidate {
107 // Prefer where-clauses. As in select, if there are multiple
108 // candidates, we prefer where-clause candidates over impls. This
109 // may seem a bit surprising, since impls are the source of
110 // "truth" in some sense, but in fact some of the impls that SEEM
111 // applicable are not, because of nested obligations. Where
112 // clauses are the safer choice. See the comment on
113 // `select::SelectionCandidate` and #21974 for more details.
114 match (current, candidate) {
115 (ParamEnv(..), ParamEnv(..)) => convert_to_ambiguous = (),
116 (ParamEnv(..), _) => return false,
117 (_, ParamEnv(..)) => unreachable!(),
118 (_, _) => convert_to_ambiguous = (),
122 Ambiguous | Error(..) => {
127 // We only ever get here when we moved from a single candidate
129 let () = convert_to_ambiguous;
135 /// Evaluates constraints of the form:
137 /// for<...> <T as Trait>::U == V
139 /// If successful, this may result in additional obligations. Also returns
140 /// the projection cache key used to track these additional obligations.
141 pub fn poly_project_and_unify_type<'cx, 'tcx>(
142 selcx: &mut SelectionContext<'cx, 'tcx>,
143 obligation: &PolyProjectionObligation<'tcx>,
144 ) -> Result<Option<Vec<PredicateObligation<'tcx>>>, MismatchedProjectionTypes<'tcx>> {
145 debug!("poly_project_and_unify_type(obligation={:?})", obligation);
147 let infcx = selcx.infcx();
148 infcx.commit_if_ok(|snapshot| {
149 let (placeholder_predicate, placeholder_map) =
150 infcx.replace_bound_vars_with_placeholders(&obligation.predicate);
152 let placeholder_obligation = obligation.with(placeholder_predicate);
153 let result = project_and_unify_type(selcx, &placeholder_obligation)?;
155 .leak_check(false, &placeholder_map, snapshot)
156 .map_err(|err| MismatchedProjectionTypes { err })?;
161 /// Evaluates constraints of the form:
163 /// <T as Trait>::U == V
165 /// If successful, this may result in additional obligations.
166 fn project_and_unify_type<'cx, 'tcx>(
167 selcx: &mut SelectionContext<'cx, 'tcx>,
168 obligation: &ProjectionObligation<'tcx>,
169 ) -> Result<Option<Vec<PredicateObligation<'tcx>>>, MismatchedProjectionTypes<'tcx>> {
170 debug!("project_and_unify_type(obligation={:?})", obligation);
172 let mut obligations = vec![];
173 let normalized_ty = match opt_normalize_projection_type(
175 obligation.param_env,
176 obligation.predicate.projection_ty,
177 obligation.cause.clone(),
178 obligation.recursion_depth,
182 None => return Ok(None),
186 "project_and_unify_type: normalized_ty={:?} obligations={:?}",
187 normalized_ty, obligations
190 let infcx = selcx.infcx();
192 .at(&obligation.cause, obligation.param_env)
193 .eq(normalized_ty, obligation.predicate.ty)
195 Ok(InferOk { obligations: inferred_obligations, value: () }) => {
196 obligations.extend(inferred_obligations);
197 Ok(Some(obligations))
200 debug!("project_and_unify_type: equating types encountered error {:?}", err);
201 Err(MismatchedProjectionTypes { err })
206 /// Normalizes any associated type projections in `value`, replacing
207 /// them with a fully resolved type where possible. The return value
208 /// combines the normalized result and any additional obligations that
209 /// were incurred as result.
210 pub fn normalize<'a, 'b, 'tcx, T>(
211 selcx: &'a mut SelectionContext<'b, 'tcx>,
212 param_env: ty::ParamEnv<'tcx>,
213 cause: ObligationCause<'tcx>,
215 ) -> Normalized<'tcx, T>
217 T: TypeFoldable<'tcx>,
219 let mut obligations = Vec::new();
220 let value = normalize_to(selcx, param_env, cause, value, &mut obligations);
221 Normalized { value, obligations }
224 pub fn normalize_to<'a, 'b, 'tcx, T>(
225 selcx: &'a mut SelectionContext<'b, 'tcx>,
226 param_env: ty::ParamEnv<'tcx>,
227 cause: ObligationCause<'tcx>,
229 obligations: &mut Vec<PredicateObligation<'tcx>>,
232 T: TypeFoldable<'tcx>,
234 normalize_with_depth_to(selcx, param_env, cause, 0, value, obligations)
237 /// As `normalize`, but with a custom depth.
238 pub fn normalize_with_depth<'a, 'b, 'tcx, T>(
239 selcx: &'a mut SelectionContext<'b, 'tcx>,
240 param_env: ty::ParamEnv<'tcx>,
241 cause: ObligationCause<'tcx>,
244 ) -> Normalized<'tcx, T>
246 T: TypeFoldable<'tcx>,
248 let mut obligations = Vec::new();
249 let value = normalize_with_depth_to(selcx, param_env, cause, depth, value, &mut obligations);
250 Normalized { value, obligations }
253 pub fn normalize_with_depth_to<'a, 'b, 'tcx, T>(
254 selcx: &'a mut SelectionContext<'b, 'tcx>,
255 param_env: ty::ParamEnv<'tcx>,
256 cause: ObligationCause<'tcx>,
259 obligations: &mut Vec<PredicateObligation<'tcx>>,
262 T: TypeFoldable<'tcx>,
264 debug!("normalize_with_depth(depth={}, value={:?})", depth, value);
265 let mut normalizer = AssocTypeNormalizer::new(selcx, param_env, cause, depth, obligations);
266 let result = normalizer.fold(value);
268 "normalize_with_depth: depth={} result={:?} with {} obligations",
271 normalizer.obligations.len()
273 debug!("normalize_with_depth: depth={} obligations={:?}", depth, normalizer.obligations);
277 struct AssocTypeNormalizer<'a, 'b, 'tcx> {
278 selcx: &'a mut SelectionContext<'b, 'tcx>,
279 param_env: ty::ParamEnv<'tcx>,
280 cause: ObligationCause<'tcx>,
281 obligations: &'a mut Vec<PredicateObligation<'tcx>>,
285 impl<'a, 'b, 'tcx> AssocTypeNormalizer<'a, 'b, 'tcx> {
287 selcx: &'a mut SelectionContext<'b, 'tcx>,
288 param_env: ty::ParamEnv<'tcx>,
289 cause: ObligationCause<'tcx>,
291 obligations: &'a mut Vec<PredicateObligation<'tcx>>,
292 ) -> AssocTypeNormalizer<'a, 'b, 'tcx> {
293 AssocTypeNormalizer { selcx, param_env, cause, obligations, depth }
296 fn fold<T: TypeFoldable<'tcx>>(&mut self, value: &T) -> T {
297 let value = self.selcx.infcx().resolve_vars_if_possible(value);
299 if !value.has_projections() { value } else { value.fold_with(self) }
303 impl<'a, 'b, 'tcx> TypeFolder<'tcx> for AssocTypeNormalizer<'a, 'b, 'tcx> {
304 fn tcx<'c>(&'c self) -> TyCtxt<'tcx> {
308 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
309 if !ty.has_projections() {
312 // We don't want to normalize associated types that occur inside of region
313 // binders, because they may contain bound regions, and we can't cope with that.
317 // for<'a> fn(<T as Foo<&'a>>::A)
319 // Instead of normalizing `<T as Foo<&'a>>::A` here, we'll
320 // normalize it when we instantiate those bound regions (which
321 // should occur eventually).
323 let ty = ty.super_fold_with(self);
325 ty::Opaque(def_id, substs) if !substs.has_escaping_bound_vars() => {
327 // Only normalize `impl Trait` after type-checking, usually in codegen.
328 match self.param_env.reveal {
329 Reveal::UserFacing => ty,
332 let recursion_limit = *self.tcx().sess.recursion_limit.get();
333 if self.depth >= recursion_limit {
334 let obligation = Obligation::with_depth(
340 self.selcx.infcx().report_overflow_error(&obligation, true);
343 let generic_ty = self.tcx().type_of(def_id);
344 let concrete_ty = generic_ty.subst(self.tcx(), substs);
346 let folded_ty = self.fold_ty(concrete_ty);
353 ty::Projection(ref data) if !data.has_escaping_bound_vars() => {
356 // (*) This is kind of hacky -- we need to be able to
357 // handle normalization within binders because
358 // otherwise we wind up a need to normalize when doing
359 // trait matching (since you can have a trait
360 // obligation like `for<'a> T::B : Fn(&'a int)`), but
361 // we can't normalize with bound regions in scope. So
362 // far now we just ignore binders but only normalize
363 // if all bound regions are gone (and then we still
364 // have to renormalize whenever we instantiate a
365 // binder). It would be better to normalize in a
366 // binding-aware fashion.
368 let normalized_ty = normalize_projection_type(
374 &mut self.obligations,
377 "AssocTypeNormalizer: depth={} normalized {:?} to {:?}, \
378 now with {} obligations",
382 self.obligations.len()
391 fn fold_const(&mut self, constant: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
392 constant.eval(self.selcx.tcx(), self.param_env)
396 #[derive(Clone, TypeFoldable)]
397 pub struct Normalized<'tcx, T> {
399 pub obligations: Vec<PredicateObligation<'tcx>>,
402 pub type NormalizedTy<'tcx> = Normalized<'tcx, Ty<'tcx>>;
404 impl<'tcx, T> Normalized<'tcx, T> {
405 pub fn with<U>(self, value: U) -> Normalized<'tcx, U> {
406 Normalized { value: value, obligations: self.obligations }
410 /// The guts of `normalize`: normalize a specific projection like `<T
411 /// as Trait>::Item`. The result is always a type (and possibly
412 /// additional obligations). If ambiguity arises, which implies that
413 /// there are unresolved type variables in the projection, we will
414 /// substitute a fresh type variable `$X` and generate a new
415 /// obligation `<T as Trait>::Item == $X` for later.
416 pub fn normalize_projection_type<'a, 'b, 'tcx>(
417 selcx: &'a mut SelectionContext<'b, 'tcx>,
418 param_env: ty::ParamEnv<'tcx>,
419 projection_ty: ty::ProjectionTy<'tcx>,
420 cause: ObligationCause<'tcx>,
422 obligations: &mut Vec<PredicateObligation<'tcx>>,
424 opt_normalize_projection_type(
432 .unwrap_or_else(move || {
433 // if we bottom out in ambiguity, create a type variable
434 // and a deferred predicate to resolve this when more type
435 // information is available.
437 let tcx = selcx.infcx().tcx;
438 let def_id = projection_ty.item_def_id;
439 let ty_var = selcx.infcx().next_ty_var(TypeVariableOrigin {
440 kind: TypeVariableOriginKind::NormalizeProjectionType,
441 span: tcx.def_span(def_id),
443 let projection = ty::Binder::dummy(ty::ProjectionPredicate { projection_ty, ty: ty_var });
445 Obligation::with_depth(cause, depth + 1, param_env, projection.to_predicate());
446 obligations.push(obligation);
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). Returns `None` in the case of ambiguity,
454 /// which indicates that there are unbound type variables.
456 /// This function used to return `Option<NormalizedTy<'tcx>>`, which contains a
457 /// `Ty<'tcx>` and an obligations vector. But that obligation vector was very
458 /// often immediately appended to another obligations vector. So now this
459 /// function takes an obligations vector and appends to it directly, which is
460 /// slightly uglier but avoids the need for an extra short-lived allocation.
461 fn opt_normalize_projection_type<'a, 'b, 'tcx>(
462 selcx: &'a mut SelectionContext<'b, 'tcx>,
463 param_env: ty::ParamEnv<'tcx>,
464 projection_ty: ty::ProjectionTy<'tcx>,
465 cause: ObligationCause<'tcx>,
467 obligations: &mut Vec<PredicateObligation<'tcx>>,
468 ) -> Option<Ty<'tcx>> {
469 let infcx = selcx.infcx();
471 let projection_ty = infcx.resolve_vars_if_possible(&projection_ty);
472 let cache_key = ProjectionCacheKey { ty: projection_ty };
475 "opt_normalize_projection_type(\
476 projection_ty={:?}, \
481 // FIXME(#20304) For now, I am caching here, which is good, but it
482 // means we don't capture the type variables that are created in
483 // the case of ambiguity. Which means we may create a large stream
484 // of such variables. OTOH, if we move the caching up a level, we
485 // would not benefit from caching when proving `T: Trait<U=Foo>`
486 // bounds. It might be the case that we want two distinct caches,
487 // or else another kind of cache entry.
489 let cache_result = infcx.inner.borrow_mut().projection_cache.try_start(cache_key);
492 Err(ProjectionCacheEntry::Ambiguous) => {
493 // If we found ambiguity the last time, that generally
494 // means we will continue to do so until some type in the
495 // key changes (and we know it hasn't, because we just
496 // fully resolved it). One exception though is closure
497 // types, which can transition from having a fixed kind to
498 // no kind with no visible change in the key.
500 // FIXME(#32286) refactor this so that closure type
503 "opt_normalize_projection_type: \
504 found cache entry: ambiguous"
506 if !projection_ty.has_closure_types() {
510 Err(ProjectionCacheEntry::InProgress) => {
511 // If while normalized A::B, we are asked to normalize
512 // A::B, just return A::B itself. This is a conservative
513 // answer, in the sense that A::B *is* clearly equivalent
514 // to A::B, though there may be a better value we can
517 // Under lazy normalization, this can arise when
518 // bootstrapping. That is, imagine an environment with a
519 // where-clause like `A::B == u32`. Now, if we are asked
520 // to normalize `A::B`, we will want to check the
521 // where-clauses in scope. So we will try to unify `A::B`
522 // with `A::B`, which can trigger a recursive
523 // normalization. In that case, I think we will want this code:
526 // let ty = selcx.tcx().mk_projection(projection_ty.item_def_id,
527 // projection_ty.substs;
528 // return Some(NormalizedTy { value: v, obligations: vec![] });
532 "opt_normalize_projection_type: \
533 found cache entry: in-progress"
536 // But for now, let's classify this as an overflow:
537 let recursion_limit = *selcx.tcx().sess.recursion_limit.get();
539 Obligation::with_depth(cause, recursion_limit, param_env, projection_ty);
540 selcx.infcx().report_overflow_error(&obligation, false);
542 Err(ProjectionCacheEntry::NormalizedTy(ty)) => {
543 // This is the hottest path in this function.
545 // If we find the value in the cache, then return it along
546 // with the obligations that went along with it. Note
547 // that, when using a fulfillment context, these
548 // obligations could in principle be ignored: they have
549 // already been registered when the cache entry was
550 // created (and hence the new ones will quickly be
551 // discarded as duplicated). But when doing trait
552 // evaluation this is not the case, and dropping the trait
553 // evaluations can causes ICEs (e.g., #43132).
555 "opt_normalize_projection_type: \
556 found normalized ty `{:?}`",
560 // Once we have inferred everything we need to know, we
561 // can ignore the `obligations` from that point on.
562 if infcx.unresolved_type_vars(&ty.value).is_none() {
563 infcx.inner.borrow_mut().projection_cache.complete_normalized(cache_key, &ty);
564 // No need to extend `obligations`.
566 obligations.extend(ty.obligations);
569 obligations.push(get_paranoid_cache_value_obligation(
576 return Some(ty.value);
578 Err(ProjectionCacheEntry::Error) => {
580 "opt_normalize_projection_type: \
583 let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth);
584 obligations.extend(result.obligations);
585 return Some(result.value);
589 let obligation = Obligation::with_depth(cause.clone(), depth, param_env, projection_ty);
590 match project_type(selcx, &obligation) {
591 Ok(ProjectedTy::Progress(Progress {
593 obligations: mut projected_obligations,
595 // if projection succeeded, then what we get out of this
596 // is also non-normalized (consider: it was derived from
597 // an impl, where-clause etc) and hence we must
601 "opt_normalize_projection_type: \
604 projected_obligations={:?}",
605 projected_ty, depth, projected_obligations
608 let result = if projected_ty.has_projections() {
609 let mut normalizer = AssocTypeNormalizer::new(
614 &mut projected_obligations,
616 let normalized_ty = normalizer.fold(&projected_ty);
619 "opt_normalize_projection_type: \
620 normalized_ty={:?} depth={}",
624 Normalized { value: normalized_ty, obligations: projected_obligations }
626 Normalized { value: projected_ty, obligations: projected_obligations }
629 let cache_value = prune_cache_value_obligations(infcx, &result);
630 infcx.inner.borrow_mut().projection_cache.insert_ty(cache_key, cache_value);
631 obligations.extend(result.obligations);
634 Ok(ProjectedTy::NoProgress(projected_ty)) => {
636 "opt_normalize_projection_type: \
637 projected_ty={:?} no progress",
640 let result = Normalized { value: projected_ty, obligations: vec![] };
641 infcx.inner.borrow_mut().projection_cache.insert_ty(cache_key, result.clone());
642 // No need to extend `obligations`.
645 Err(ProjectionTyError::TooManyCandidates) => {
647 "opt_normalize_projection_type: \
650 infcx.inner.borrow_mut().projection_cache.ambiguous(cache_key);
653 Err(ProjectionTyError::TraitSelectionError(_)) => {
654 debug!("opt_normalize_projection_type: ERROR");
655 // if we got an error processing the `T as Trait` part,
656 // just return `ty::err` but add the obligation `T :
657 // Trait`, which when processed will cause the error to be
660 infcx.inner.borrow_mut().projection_cache.error(cache_key);
661 let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth);
662 obligations.extend(result.obligations);
668 /// If there are unresolved type variables, then we need to include
669 /// any subobligations that bind them, at least until those type
670 /// variables are fully resolved.
671 fn prune_cache_value_obligations<'a, 'tcx>(
672 infcx: &'a InferCtxt<'a, 'tcx>,
673 result: &NormalizedTy<'tcx>,
674 ) -> NormalizedTy<'tcx> {
675 if infcx.unresolved_type_vars(&result.value).is_none() {
676 return NormalizedTy { value: result.value, obligations: vec![] };
679 let mut obligations: Vec<_> = result
682 .filter(|obligation| match obligation.predicate {
683 // We found a `T: Foo<X = U>` predicate, let's check
684 // if `U` references any unresolved type
685 // variables. In principle, we only care if this
686 // projection can help resolve any of the type
687 // variables found in `result.value` -- but we just
688 // check for any type variables here, for fear of
689 // indirect obligations (e.g., we project to `?0`,
690 // but we have `T: Foo<X = ?1>` and `?1: Bar<X =
692 ty::Predicate::Projection(ref data) => infcx.unresolved_type_vars(&data.ty()).is_some(),
694 // We are only interested in `T: Foo<X = U>` predicates, whre
695 // `U` references one of `unresolved_type_vars`. =)
701 obligations.shrink_to_fit();
703 NormalizedTy { value: result.value, obligations }
706 /// Whenever we give back a cache result for a projection like `<T as
707 /// Trait>::Item ==> X`, we *always* include the obligation to prove
708 /// that `T: Trait` (we may also include some other obligations). This
709 /// may or may not be necessary -- in principle, all the obligations
710 /// that must be proven to show that `T: Trait` were also returned
711 /// when the cache was first populated. But there are some vague concerns,
712 /// and so we take the precautionary measure of including `T: Trait` in
715 /// Concern #1. The current setup is fragile. Perhaps someone could
716 /// have failed to prove the concerns from when the cache was
717 /// populated, but also not have used a snapshot, in which case the
718 /// cache could remain populated even though `T: Trait` has not been
719 /// shown. In this case, the "other code" is at fault -- when you
720 /// project something, you are supposed to either have a snapshot or
721 /// else prove all the resulting obligations -- but it's still easy to
724 /// Concern #2. Even within the snapshot, if those original
725 /// obligations are not yet proven, then we are able to do projections
726 /// that may yet turn out to be wrong. This *may* lead to some sort
727 /// of trouble, though we don't have a concrete example of how that
728 /// can occur yet. But it seems risky at best.
729 fn get_paranoid_cache_value_obligation<'a, 'tcx>(
730 infcx: &'a InferCtxt<'a, 'tcx>,
731 param_env: ty::ParamEnv<'tcx>,
732 projection_ty: ty::ProjectionTy<'tcx>,
733 cause: ObligationCause<'tcx>,
735 ) -> PredicateObligation<'tcx> {
736 let trait_ref = projection_ty.trait_ref(infcx.tcx).to_poly_trait_ref();
739 recursion_depth: depth,
741 predicate: trait_ref.without_const().to_predicate(),
745 /// If we are projecting `<T as Trait>::Item`, but `T: Trait` does not
746 /// hold. In various error cases, we cannot generate a valid
747 /// normalized projection. Therefore, we create an inference variable
748 /// return an associated obligation that, when fulfilled, will lead to
751 /// Note that we used to return `Error` here, but that was quite
752 /// dubious -- the premise was that an error would *eventually* be
753 /// reported, when the obligation was processed. But in general once
754 /// you see a `Error` you are supposed to be able to assume that an
755 /// error *has been* reported, so that you can take whatever heuristic
756 /// paths you want to take. To make things worse, it was possible for
757 /// cycles to arise, where you basically had a setup like `<MyType<$0>
758 /// as Trait>::Foo == $0`. Here, normalizing `<MyType<$0> as
759 /// Trait>::Foo> to `[type error]` would lead to an obligation of
760 /// `<MyType<[type error]> as Trait>::Foo`. We are supposed to report
761 /// an error for this obligation, but we legitimately should not,
762 /// because it contains `[type error]`. Yuck! (See issue #29857 for
763 /// one case where this arose.)
764 fn normalize_to_error<'a, 'tcx>(
765 selcx: &mut SelectionContext<'a, 'tcx>,
766 param_env: ty::ParamEnv<'tcx>,
767 projection_ty: ty::ProjectionTy<'tcx>,
768 cause: ObligationCause<'tcx>,
770 ) -> NormalizedTy<'tcx> {
771 let trait_ref = projection_ty.trait_ref(selcx.tcx()).to_poly_trait_ref();
772 let trait_obligation = Obligation {
774 recursion_depth: depth,
776 predicate: trait_ref.without_const().to_predicate(),
778 let tcx = selcx.infcx().tcx;
779 let def_id = projection_ty.item_def_id;
780 let new_value = selcx.infcx().next_ty_var(TypeVariableOrigin {
781 kind: TypeVariableOriginKind::NormalizeProjectionType,
782 span: tcx.def_span(def_id),
784 Normalized { value: new_value, obligations: vec![trait_obligation] }
787 enum ProjectedTy<'tcx> {
788 Progress(Progress<'tcx>),
789 NoProgress(Ty<'tcx>),
792 struct Progress<'tcx> {
794 obligations: Vec<PredicateObligation<'tcx>>,
797 impl<'tcx> Progress<'tcx> {
798 fn error(tcx: TyCtxt<'tcx>) -> Self {
799 Progress { ty: tcx.types.err, obligations: vec![] }
802 fn with_addl_obligations(mut self, mut obligations: Vec<PredicateObligation<'tcx>>) -> Self {
804 "with_addl_obligations: self.obligations.len={} obligations.len={}",
805 self.obligations.len(),
810 "with_addl_obligations: self.obligations={:?} obligations={:?}",
811 self.obligations, obligations
814 self.obligations.append(&mut obligations);
819 /// Computes the result of a projection type (if we can).
822 /// - `obligation` must be fully normalized
823 fn project_type<'cx, 'tcx>(
824 selcx: &mut SelectionContext<'cx, 'tcx>,
825 obligation: &ProjectionTyObligation<'tcx>,
826 ) -> Result<ProjectedTy<'tcx>, ProjectionTyError<'tcx>> {
827 debug!("project(obligation={:?})", obligation);
829 let recursion_limit = *selcx.tcx().sess.recursion_limit.get();
830 if obligation.recursion_depth >= recursion_limit {
831 debug!("project: overflow!");
832 return Err(ProjectionTyError::TraitSelectionError(SelectionError::Overflow));
835 let obligation_trait_ref = &obligation.predicate.trait_ref(selcx.tcx());
837 debug!("project: obligation_trait_ref={:?}", obligation_trait_ref);
839 if obligation_trait_ref.references_error() {
840 return Ok(ProjectedTy::Progress(Progress::error(selcx.tcx())));
843 let mut candidates = ProjectionTyCandidateSet::None;
845 // Make sure that the following procedures are kept in order. ParamEnv
846 // needs to be first because it has highest priority, and Select checks
847 // the return value of push_candidate which assumes it's ran at last.
848 assemble_candidates_from_param_env(selcx, obligation, &obligation_trait_ref, &mut candidates);
850 assemble_candidates_from_trait_def(selcx, obligation, &obligation_trait_ref, &mut candidates);
852 assemble_candidates_from_impls(selcx, obligation, &obligation_trait_ref, &mut candidates);
855 ProjectionTyCandidateSet::Single(candidate) => Ok(ProjectedTy::Progress(
856 confirm_candidate(selcx, obligation, &obligation_trait_ref, candidate),
858 ProjectionTyCandidateSet::None => Ok(ProjectedTy::NoProgress(
861 .mk_projection(obligation.predicate.item_def_id, obligation.predicate.substs),
863 // Error occurred while trying to processing impls.
864 ProjectionTyCandidateSet::Error(e) => Err(ProjectionTyError::TraitSelectionError(e)),
865 // Inherent ambiguity that prevents us from even enumerating the
867 ProjectionTyCandidateSet::Ambiguous => Err(ProjectionTyError::TooManyCandidates),
871 /// The first thing we have to do is scan through the parameter
872 /// environment to see whether there are any projection predicates
873 /// there that can answer this question.
874 fn assemble_candidates_from_param_env<'cx, 'tcx>(
875 selcx: &mut SelectionContext<'cx, 'tcx>,
876 obligation: &ProjectionTyObligation<'tcx>,
877 obligation_trait_ref: &ty::TraitRef<'tcx>,
878 candidate_set: &mut ProjectionTyCandidateSet<'tcx>,
880 debug!("assemble_candidates_from_param_env(..)");
881 assemble_candidates_from_predicates(
884 obligation_trait_ref,
886 ProjectionTyCandidate::ParamEnv,
887 obligation.param_env.caller_bounds.iter().cloned(),
891 /// In the case of a nested projection like <<A as Foo>::FooT as Bar>::BarT, we may find
892 /// that the definition of `Foo` has some clues:
896 /// type FooT : Bar<BarT=i32>
900 /// Here, for example, we could conclude that the result is `i32`.
901 fn assemble_candidates_from_trait_def<'cx, 'tcx>(
902 selcx: &mut SelectionContext<'cx, 'tcx>,
903 obligation: &ProjectionTyObligation<'tcx>,
904 obligation_trait_ref: &ty::TraitRef<'tcx>,
905 candidate_set: &mut ProjectionTyCandidateSet<'tcx>,
907 debug!("assemble_candidates_from_trait_def(..)");
909 let tcx = selcx.tcx();
910 // Check whether the self-type is itself a projection.
911 let (def_id, substs) = match obligation_trait_ref.self_ty().kind {
912 ty::Projection(ref data) => (data.trait_ref(tcx).def_id, data.substs),
913 ty::Opaque(def_id, substs) => (def_id, substs),
914 ty::Infer(ty::TyVar(_)) => {
915 // If the self-type is an inference variable, then it MAY wind up
916 // being a projected type, so induce an ambiguity.
917 candidate_set.mark_ambiguous();
923 // If so, extract what we know from the trait and try to come up with a good answer.
924 let trait_predicates = tcx.predicates_of(def_id);
925 let bounds = trait_predicates.instantiate(tcx, substs);
926 let bounds = elaborate_predicates(tcx, bounds.predicates);
927 assemble_candidates_from_predicates(
930 obligation_trait_ref,
932 ProjectionTyCandidate::TraitDef,
937 fn assemble_candidates_from_predicates<'cx, 'tcx, I>(
938 selcx: &mut SelectionContext<'cx, 'tcx>,
939 obligation: &ProjectionTyObligation<'tcx>,
940 obligation_trait_ref: &ty::TraitRef<'tcx>,
941 candidate_set: &mut ProjectionTyCandidateSet<'tcx>,
942 ctor: fn(ty::PolyProjectionPredicate<'tcx>) -> ProjectionTyCandidate<'tcx>,
945 I: IntoIterator<Item = ty::Predicate<'tcx>>,
947 debug!("assemble_candidates_from_predicates(obligation={:?})", obligation);
948 let infcx = selcx.infcx();
949 for predicate in env_predicates {
950 debug!("assemble_candidates_from_predicates: predicate={:?}", predicate);
951 if let ty::Predicate::Projection(data) = predicate {
952 let same_def_id = data.projection_def_id() == obligation.predicate.item_def_id;
954 let is_match = same_def_id
956 let data_poly_trait_ref = data.to_poly_trait_ref(infcx.tcx);
957 let obligation_poly_trait_ref = obligation_trait_ref.to_poly_trait_ref();
959 .at(&obligation.cause, obligation.param_env)
960 .sup(obligation_poly_trait_ref, data_poly_trait_ref)
961 .map(|InferOk { obligations: _, value: () }| {
962 // FIXME(#32730) -- do we need to take obligations
963 // into account in any way? At the moment, no.
969 "assemble_candidates_from_predicates: candidate={:?} \
970 is_match={} same_def_id={}",
971 data, is_match, same_def_id
975 candidate_set.push_candidate(ctor(data));
981 fn assemble_candidates_from_impls<'cx, 'tcx>(
982 selcx: &mut SelectionContext<'cx, 'tcx>,
983 obligation: &ProjectionTyObligation<'tcx>,
984 obligation_trait_ref: &ty::TraitRef<'tcx>,
985 candidate_set: &mut ProjectionTyCandidateSet<'tcx>,
987 // If we are resolving `<T as TraitRef<...>>::Item == Type`,
988 // start out by selecting the predicate `T as TraitRef<...>`:
989 let poly_trait_ref = obligation_trait_ref.to_poly_trait_ref();
990 let trait_obligation = obligation.with(poly_trait_ref.to_poly_trait_predicate());
991 let _ = selcx.infcx().commit_if_ok(|_| {
992 let vtable = match selcx.select(&trait_obligation) {
993 Ok(Some(vtable)) => vtable,
995 candidate_set.mark_ambiguous();
999 debug!("assemble_candidates_from_impls: selection error {:?}", e);
1000 candidate_set.mark_error(e);
1005 let eligible = match &vtable {
1006 super::VtableClosure(_)
1007 | super::VtableGenerator(_)
1008 | super::VtableFnPointer(_)
1009 | super::VtableObject(_)
1010 | super::VtableTraitAlias(_) => {
1011 debug!("assemble_candidates_from_impls: vtable={:?}", vtable);
1014 super::VtableImpl(impl_data) => {
1015 // We have to be careful when projecting out of an
1016 // impl because of specialization. If we are not in
1017 // codegen (i.e., projection mode is not "any"), and the
1018 // impl's type is declared as default, then we disable
1019 // projection (even if the trait ref is fully
1020 // monomorphic). In the case where trait ref is not
1021 // fully monomorphic (i.e., includes type parameters),
1022 // this is because those type parameters may
1023 // ultimately be bound to types from other crates that
1024 // may have specialized impls we can't see. In the
1025 // case where the trait ref IS fully monomorphic, this
1026 // is a policy decision that we made in the RFC in
1027 // order to preserve flexibility for the crate that
1028 // defined the specializable impl to specialize later
1029 // for existing types.
1031 // In either case, we handle this by not adding a
1032 // candidate for an impl if it contains a `default`
1035 // NOTE: This should be kept in sync with the similar code in
1036 // `rustc::ty::instance::resolve_associated_item()`.
1038 assoc_ty_def(selcx, impl_data.impl_def_id, obligation.predicate.item_def_id);
1040 let is_default = if node_item.node.is_from_trait() {
1041 // If true, the impl inherited a `type Foo = Bar`
1042 // given in the trait, which is implicitly default.
1043 // Otherwise, the impl did not specify `type` and
1044 // neither did the trait:
1047 // trait Foo { type T; }
1048 // impl Foo for Bar { }
1051 // This is an error, but it will be
1052 // reported in `check_impl_items_against_trait`.
1053 // We accept it here but will flag it as
1054 // an error when we confirm the candidate
1055 // (which will ultimately lead to `normalize_to_error`
1059 // If we're looking at a trait *impl*, the item is
1060 // specializable if the impl or the item are marked
1062 node_item.item.defaultness.is_default()
1063 || super::util::impl_is_default(selcx.tcx(), node_item.node.def_id())
1067 // Non-specializable items are always projectable
1070 // Only reveal a specializable default if we're past type-checking
1071 // and the obligation is monomorphic, otherwise passes such as
1072 // transmute checking and polymorphic MIR optimizations could
1073 // get a result which isn't correct for all monomorphizations.
1074 true if obligation.param_env.reveal == Reveal::All => {
1075 // NOTE(eddyb) inference variables can resolve to parameters, so
1076 // assume `poly_trait_ref` isn't monomorphic, if it contains any.
1077 let poly_trait_ref =
1078 selcx.infcx().resolve_vars_if_possible(&poly_trait_ref);
1079 !poly_trait_ref.needs_infer() && !poly_trait_ref.needs_subst()
1084 "assemble_candidates_from_impls: not eligible due to default: \
1085 assoc_ty={} predicate={}",
1086 selcx.tcx().def_path_str(node_item.item.def_id),
1087 obligation.predicate,
1093 super::VtableParam(..) => {
1094 // This case tell us nothing about the value of an
1095 // associated type. Consider:
1098 // trait SomeTrait { type Foo; }
1099 // fn foo<T:SomeTrait>(...) { }
1102 // If the user writes `<T as SomeTrait>::Foo`, then the `T
1103 // : SomeTrait` binding does not help us decide what the
1104 // type `Foo` is (at least, not more specifically than
1105 // what we already knew).
1107 // But wait, you say! What about an example like this:
1110 // fn bar<T:SomeTrait<Foo=usize>>(...) { ... }
1113 // Doesn't the `T : Sometrait<Foo=usize>` predicate help
1114 // resolve `T::Foo`? And of course it does, but in fact
1115 // that single predicate is desugared into two predicates
1116 // in the compiler: a trait predicate (`T : SomeTrait`) and a
1117 // projection. And the projection where clause is handled
1118 // in `assemble_candidates_from_param_env`.
1121 super::VtableAutoImpl(..) | super::VtableBuiltin(..) => {
1122 // These traits have no associated types.
1124 obligation.cause.span,
1125 "Cannot project an associated type from `{:?}`",
1132 if candidate_set.push_candidate(ProjectionTyCandidate::Select(vtable)) {
1143 fn confirm_candidate<'cx, 'tcx>(
1144 selcx: &mut SelectionContext<'cx, 'tcx>,
1145 obligation: &ProjectionTyObligation<'tcx>,
1146 obligation_trait_ref: &ty::TraitRef<'tcx>,
1147 candidate: ProjectionTyCandidate<'tcx>,
1148 ) -> Progress<'tcx> {
1149 debug!("confirm_candidate(candidate={:?}, obligation={:?})", candidate, obligation);
1152 ProjectionTyCandidate::ParamEnv(poly_projection)
1153 | ProjectionTyCandidate::TraitDef(poly_projection) => {
1154 confirm_param_env_candidate(selcx, obligation, poly_projection)
1157 ProjectionTyCandidate::Select(vtable) => {
1158 confirm_select_candidate(selcx, obligation, obligation_trait_ref, vtable)
1163 fn confirm_select_candidate<'cx, 'tcx>(
1164 selcx: &mut SelectionContext<'cx, 'tcx>,
1165 obligation: &ProjectionTyObligation<'tcx>,
1166 obligation_trait_ref: &ty::TraitRef<'tcx>,
1167 vtable: Selection<'tcx>,
1168 ) -> Progress<'tcx> {
1170 super::VtableImpl(data) => confirm_impl_candidate(selcx, obligation, data),
1171 super::VtableGenerator(data) => confirm_generator_candidate(selcx, obligation, data),
1172 super::VtableClosure(data) => confirm_closure_candidate(selcx, obligation, data),
1173 super::VtableFnPointer(data) => confirm_fn_pointer_candidate(selcx, obligation, data),
1174 super::VtableObject(_) => confirm_object_candidate(selcx, obligation, obligation_trait_ref),
1175 super::VtableAutoImpl(..)
1176 | super::VtableParam(..)
1177 | super::VtableBuiltin(..)
1178 | super::VtableTraitAlias(..) =>
1179 // we don't create Select candidates with this kind of resolution
1182 obligation.cause.span,
1183 "Cannot project an associated type from `{:?}`",
1190 fn confirm_object_candidate<'cx, 'tcx>(
1191 selcx: &mut SelectionContext<'cx, 'tcx>,
1192 obligation: &ProjectionTyObligation<'tcx>,
1193 obligation_trait_ref: &ty::TraitRef<'tcx>,
1194 ) -> Progress<'tcx> {
1195 let self_ty = obligation_trait_ref.self_ty();
1196 let object_ty = selcx.infcx().shallow_resolve(self_ty);
1197 debug!("confirm_object_candidate(object_ty={:?})", object_ty);
1198 let data = match object_ty.kind {
1199 ty::Dynamic(ref data, ..) => data,
1201 obligation.cause.span,
1202 "confirm_object_candidate called with non-object: {:?}",
1206 let env_predicates = data
1207 .projection_bounds()
1208 .map(|p| p.with_self_ty(selcx.tcx(), object_ty).to_predicate())
1210 let env_predicate = {
1211 let env_predicates = elaborate_predicates(selcx.tcx(), env_predicates);
1213 // select only those projections that are actually projecting an
1214 // item with the correct name
1215 let env_predicates = env_predicates.filter_map(|p| match p {
1216 ty::Predicate::Projection(data) => {
1217 if data.projection_def_id() == obligation.predicate.item_def_id {
1226 // select those with a relevant trait-ref
1227 let mut env_predicates = env_predicates.filter(|data| {
1228 let data_poly_trait_ref = data.to_poly_trait_ref(selcx.tcx());
1229 let obligation_poly_trait_ref = obligation_trait_ref.to_poly_trait_ref();
1230 selcx.infcx().probe(|_| {
1233 .at(&obligation.cause, obligation.param_env)
1234 .sup(obligation_poly_trait_ref, data_poly_trait_ref)
1239 // select the first matching one; there really ought to be one or
1240 // else the object type is not WF, since an object type should
1241 // include all of its projections explicitly
1242 match env_predicates.next() {
1243 Some(env_predicate) => env_predicate,
1246 "confirm_object_candidate: no env-predicate \
1247 found in object type `{:?}`; ill-formed",
1250 return Progress::error(selcx.tcx());
1255 confirm_param_env_candidate(selcx, obligation, env_predicate)
1258 fn confirm_generator_candidate<'cx, 'tcx>(
1259 selcx: &mut SelectionContext<'cx, 'tcx>,
1260 obligation: &ProjectionTyObligation<'tcx>,
1261 vtable: VtableGeneratorData<'tcx, PredicateObligation<'tcx>>,
1262 ) -> Progress<'tcx> {
1263 let gen_sig = vtable.substs.as_generator().poly_sig(vtable.generator_def_id, selcx.tcx());
1264 let Normalized { value: gen_sig, obligations } = normalize_with_depth(
1266 obligation.param_env,
1267 obligation.cause.clone(),
1268 obligation.recursion_depth + 1,
1273 "confirm_generator_candidate: obligation={:?},gen_sig={:?},obligations={:?}",
1274 obligation, gen_sig, obligations
1277 let tcx = selcx.tcx();
1279 let gen_def_id = tcx.lang_items().gen_trait().unwrap();
1281 let predicate = super::util::generator_trait_ref_and_outputs(
1284 obligation.predicate.self_ty(),
1287 .map_bound(|(trait_ref, yield_ty, return_ty)| {
1288 let name = tcx.associated_item(obligation.predicate.item_def_id).ident.name;
1289 let ty = if name == sym::Return {
1291 } else if name == sym::Yield {
1297 ty::ProjectionPredicate {
1298 projection_ty: ty::ProjectionTy {
1299 substs: trait_ref.substs,
1300 item_def_id: obligation.predicate.item_def_id,
1306 confirm_param_env_candidate(selcx, obligation, predicate)
1307 .with_addl_obligations(vtable.nested)
1308 .with_addl_obligations(obligations)
1311 fn confirm_fn_pointer_candidate<'cx, 'tcx>(
1312 selcx: &mut SelectionContext<'cx, 'tcx>,
1313 obligation: &ProjectionTyObligation<'tcx>,
1314 fn_pointer_vtable: VtableFnPointerData<'tcx, PredicateObligation<'tcx>>,
1315 ) -> Progress<'tcx> {
1316 let fn_type = selcx.infcx().shallow_resolve(fn_pointer_vtable.fn_ty);
1317 let sig = fn_type.fn_sig(selcx.tcx());
1318 let Normalized { value: sig, obligations } = normalize_with_depth(
1320 obligation.param_env,
1321 obligation.cause.clone(),
1322 obligation.recursion_depth + 1,
1326 confirm_callable_candidate(selcx, obligation, sig, util::TupleArgumentsFlag::Yes)
1327 .with_addl_obligations(fn_pointer_vtable.nested)
1328 .with_addl_obligations(obligations)
1331 fn confirm_closure_candidate<'cx, 'tcx>(
1332 selcx: &mut SelectionContext<'cx, 'tcx>,
1333 obligation: &ProjectionTyObligation<'tcx>,
1334 vtable: VtableClosureData<'tcx, PredicateObligation<'tcx>>,
1335 ) -> Progress<'tcx> {
1336 let tcx = selcx.tcx();
1337 let infcx = selcx.infcx();
1338 let closure_sig_ty = vtable.substs.as_closure().sig_ty(vtable.closure_def_id, tcx);
1339 let closure_sig = infcx.shallow_resolve(closure_sig_ty).fn_sig(tcx);
1340 let Normalized { value: closure_sig, obligations } = normalize_with_depth(
1342 obligation.param_env,
1343 obligation.cause.clone(),
1344 obligation.recursion_depth + 1,
1349 "confirm_closure_candidate: obligation={:?},closure_sig={:?},obligations={:?}",
1350 obligation, closure_sig, obligations
1353 confirm_callable_candidate(selcx, obligation, closure_sig, util::TupleArgumentsFlag::No)
1354 .with_addl_obligations(vtable.nested)
1355 .with_addl_obligations(obligations)
1358 fn confirm_callable_candidate<'cx, 'tcx>(
1359 selcx: &mut SelectionContext<'cx, 'tcx>,
1360 obligation: &ProjectionTyObligation<'tcx>,
1361 fn_sig: ty::PolyFnSig<'tcx>,
1362 flag: util::TupleArgumentsFlag,
1363 ) -> Progress<'tcx> {
1364 let tcx = selcx.tcx();
1366 debug!("confirm_callable_candidate({:?},{:?})", obligation, fn_sig);
1368 // the `Output` associated type is declared on `FnOnce`
1369 let fn_once_def_id = tcx.lang_items().fn_once_trait().unwrap();
1371 let predicate = super::util::closure_trait_ref_and_return_type(
1374 obligation.predicate.self_ty(),
1378 .map_bound(|(trait_ref, ret_type)| ty::ProjectionPredicate {
1379 projection_ty: ty::ProjectionTy::from_ref_and_name(
1382 Ident::with_dummy_span(rustc_hir::FN_OUTPUT_NAME),
1387 confirm_param_env_candidate(selcx, obligation, predicate)
1390 fn confirm_param_env_candidate<'cx, 'tcx>(
1391 selcx: &mut SelectionContext<'cx, 'tcx>,
1392 obligation: &ProjectionTyObligation<'tcx>,
1393 poly_cache_entry: ty::PolyProjectionPredicate<'tcx>,
1394 ) -> Progress<'tcx> {
1395 let infcx = selcx.infcx();
1396 let cause = &obligation.cause;
1397 let param_env = obligation.param_env;
1399 let (cache_entry, _) = infcx.replace_bound_vars_with_fresh_vars(
1401 LateBoundRegionConversionTime::HigherRankedType,
1405 let cache_trait_ref = cache_entry.projection_ty.trait_ref(infcx.tcx);
1406 let obligation_trait_ref = obligation.predicate.trait_ref(infcx.tcx);
1407 match infcx.at(cause, param_env).eq(cache_trait_ref, obligation_trait_ref) {
1408 Ok(InferOk { value: _, obligations }) => Progress { ty: cache_entry.ty, obligations },
1411 "Failed to unify obligation `{:?}` with poly_projection `{:?}`: {:?}",
1412 obligation, poly_cache_entry, e,
1414 debug!("confirm_param_env_candidate: {}", msg);
1415 infcx.tcx.sess.delay_span_bug(obligation.cause.span, &msg);
1416 Progress { ty: infcx.tcx.types.err, obligations: vec![] }
1421 fn confirm_impl_candidate<'cx, 'tcx>(
1422 selcx: &mut SelectionContext<'cx, 'tcx>,
1423 obligation: &ProjectionTyObligation<'tcx>,
1424 impl_vtable: VtableImplData<'tcx, PredicateObligation<'tcx>>,
1425 ) -> Progress<'tcx> {
1426 let tcx = selcx.tcx();
1428 let VtableImplData { impl_def_id, substs, nested } = impl_vtable;
1429 let assoc_item_id = obligation.predicate.item_def_id;
1430 let trait_def_id = tcx.trait_id_of_impl(impl_def_id).unwrap();
1432 let param_env = obligation.param_env;
1433 let assoc_ty = assoc_ty_def(selcx, impl_def_id, assoc_item_id);
1435 if !assoc_ty.item.defaultness.has_value() {
1436 // This means that the impl is missing a definition for the
1437 // associated type. This error will be reported by the type
1438 // checker method `check_impl_items_against_trait`, so here we
1439 // just return Error.
1441 "confirm_impl_candidate: no associated type {:?} for {:?}",
1442 assoc_ty.item.ident, obligation.predicate
1444 return Progress { ty: tcx.types.err, obligations: nested };
1446 let substs = obligation.predicate.substs.rebase_onto(tcx, trait_def_id, substs);
1447 let substs = translate_substs(selcx.infcx(), param_env, impl_def_id, substs, assoc_ty.node);
1448 let ty = if let ty::AssocKind::OpaqueTy = assoc_ty.item.kind {
1449 let item_substs = InternalSubsts::identity_for_item(tcx, assoc_ty.item.def_id);
1450 tcx.mk_opaque(assoc_ty.item.def_id, item_substs)
1452 tcx.type_of(assoc_ty.item.def_id)
1454 if substs.len() != tcx.generics_of(assoc_ty.item.def_id).count() {
1456 .delay_span_bug(DUMMY_SP, "impl item and trait item have different parameter counts");
1457 Progress { ty: tcx.types.err, obligations: nested }
1459 Progress { ty: ty.subst(tcx, substs), obligations: nested }
1463 /// Locate the definition of an associated type in the specialization hierarchy,
1464 /// starting from the given impl.
1466 /// Based on the "projection mode", this lookup may in fact only examine the
1467 /// topmost impl. See the comments for `Reveal` for more details.
1469 selcx: &SelectionContext<'_, '_>,
1471 assoc_ty_def_id: DefId,
1472 ) -> specialization_graph::NodeItem<ty::AssocItem> {
1473 let tcx = selcx.tcx();
1474 let assoc_ty_name = tcx.associated_item(assoc_ty_def_id).ident;
1475 let trait_def_id = tcx.impl_trait_ref(impl_def_id).unwrap().def_id;
1476 let trait_def = tcx.trait_def(trait_def_id);
1478 // This function may be called while we are still building the
1479 // specialization graph that is queried below (via TraidDef::ancestors()),
1480 // so, in order to avoid unnecessary infinite recursion, we manually look
1481 // for the associated item at the given impl.
1482 // If there is no such item in that impl, this function will fail with a
1483 // cycle error if the specialization graph is currently being built.
1484 let impl_node = specialization_graph::Node::Impl(impl_def_id);
1485 for item in impl_node.items(tcx) {
1486 if matches!(item.kind, ty::AssocKind::Type | ty::AssocKind::OpaqueTy)
1487 && tcx.hygienic_eq(item.ident, assoc_ty_name, trait_def_id)
1489 return specialization_graph::NodeItem {
1490 node: specialization_graph::Node::Impl(impl_def_id),
1496 if let Some(assoc_item) =
1497 trait_def.ancestors(tcx, impl_def_id).leaf_def(tcx, assoc_ty_name, ty::AssocKind::Type)
1501 // This is saying that neither the trait nor
1502 // the impl contain a definition for this
1503 // associated type. Normally this situation
1504 // could only arise through a compiler bug --
1505 // if the user wrote a bad item name, it
1506 // should have failed in astconv.
1507 bug!("No associated type `{}` for {}", assoc_ty_name, tcx.def_path_str(impl_def_id))
1513 /// The projection cache. Unlike the standard caches, this can include
1514 /// infcx-dependent type variables, therefore we have to roll the
1515 /// cache back each time we roll a snapshot back, to avoid assumptions
1516 /// on yet-unresolved inference variables. Types with placeholder
1517 /// regions also have to be removed when the respective snapshot ends.
1519 /// Because of that, projection cache entries can be "stranded" and left
1520 /// inaccessible when type variables inside the key are resolved. We make no
1521 /// attempt to recover or remove "stranded" entries, but rather let them be
1522 /// (for the lifetime of the infcx).
1524 /// Entries in the projection cache might contain inference variables
1525 /// that will be resolved by obligations on the projection cache entry (e.g.,
1526 /// when a type parameter in the associated type is constrained through
1527 /// an "RFC 447" projection on the impl).
1529 /// When working with a fulfillment context, the derived obligations of each
1530 /// projection cache entry will be registered on the fulfillcx, so any users
1531 /// that can wait for a fulfillcx fixed point need not care about this. However,
1532 /// users that don't wait for a fixed point (e.g., trait evaluation) have to
1533 /// resolve the obligations themselves to make sure the projected result is
1534 /// ok and avoid issues like #43132.
1536 /// If that is done, after evaluation the obligations, it is a good idea to
1537 /// call `ProjectionCache::complete` to make sure the obligations won't be
1538 /// re-evaluated and avoid an exponential worst-case.
1540 // FIXME: we probably also want some sort of cross-infcx cache here to
1541 // reduce the amount of duplication. Let's see what we get with the Chalk reforms.
1543 pub struct ProjectionCache<'tcx> {
1544 map: SnapshotMap<ProjectionCacheKey<'tcx>, ProjectionCacheEntry<'tcx>>,
1547 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
1548 pub struct ProjectionCacheKey<'tcx> {
1549 ty: ty::ProjectionTy<'tcx>,
1552 impl<'cx, 'tcx> ProjectionCacheKey<'tcx> {
1553 pub fn from_poly_projection_predicate(
1554 selcx: &mut SelectionContext<'cx, 'tcx>,
1555 predicate: &ty::PolyProjectionPredicate<'tcx>,
1557 let infcx = selcx.infcx();
1558 // We don't do cross-snapshot caching of obligations with escaping regions,
1559 // so there's no cache key to use
1560 predicate.no_bound_vars().map(|predicate| ProjectionCacheKey {
1561 // We don't attempt to match up with a specific type-variable state
1562 // from a specific call to `opt_normalize_projection_type` - if
1563 // there's no precise match, the original cache entry is "stranded"
1565 ty: infcx.resolve_vars_if_possible(&predicate.projection_ty),
1570 #[derive(Clone, Debug)]
1571 enum ProjectionCacheEntry<'tcx> {
1575 NormalizedTy(NormalizedTy<'tcx>),
1578 // N.B., intentionally not Clone
1579 pub struct ProjectionCacheSnapshot {
1583 impl<'tcx> ProjectionCache<'tcx> {
1584 pub fn clear(&mut self) {
1588 pub fn snapshot(&mut self) -> ProjectionCacheSnapshot {
1589 ProjectionCacheSnapshot { snapshot: self.map.snapshot() }
1592 pub fn rollback_to(&mut self, snapshot: ProjectionCacheSnapshot) {
1593 self.map.rollback_to(snapshot.snapshot);
1596 pub fn rollback_placeholder(&mut self, snapshot: &ProjectionCacheSnapshot) {
1597 self.map.partial_rollback(&snapshot.snapshot, &|k| k.ty.has_re_placeholders());
1600 pub fn commit(&mut self, snapshot: ProjectionCacheSnapshot) {
1601 self.map.commit(snapshot.snapshot);
1604 /// Try to start normalize `key`; returns an error if
1605 /// normalization already occurred (this error corresponds to a
1606 /// cache hit, so it's actually a good thing).
1609 key: ProjectionCacheKey<'tcx>,
1610 ) -> Result<(), ProjectionCacheEntry<'tcx>> {
1611 if let Some(entry) = self.map.get(&key) {
1612 return Err(entry.clone());
1615 self.map.insert(key, ProjectionCacheEntry::InProgress);
1619 /// Indicates that `key` was normalized to `value`.
1620 fn insert_ty(&mut self, key: ProjectionCacheKey<'tcx>, value: NormalizedTy<'tcx>) {
1622 "ProjectionCacheEntry::insert_ty: adding cache entry: key={:?}, value={:?}",
1625 let fresh_key = self.map.insert(key, ProjectionCacheEntry::NormalizedTy(value));
1626 assert!(!fresh_key, "never started projecting `{:?}`", key);
1629 /// Mark the relevant projection cache key as having its derived obligations
1630 /// complete, so they won't have to be re-computed (this is OK to do in a
1631 /// snapshot - if the snapshot is rolled back, the obligations will be
1632 /// marked as incomplete again).
1633 pub fn complete(&mut self, key: ProjectionCacheKey<'tcx>) {
1634 let ty = match self.map.get(&key) {
1635 Some(&ProjectionCacheEntry::NormalizedTy(ref ty)) => {
1636 debug!("ProjectionCacheEntry::complete({:?}) - completing {:?}", key, ty);
1640 // Type inference could "strand behind" old cache entries. Leave
1641 // them alone for now.
1642 debug!("ProjectionCacheEntry::complete({:?}) - ignoring {:?}", key, value);
1649 ProjectionCacheEntry::NormalizedTy(Normalized { value: ty, obligations: vec![] }),
1653 /// A specialized version of `complete` for when the key's value is known
1654 /// to be a NormalizedTy.
1655 pub fn complete_normalized(&mut self, key: ProjectionCacheKey<'tcx>, ty: &NormalizedTy<'tcx>) {
1656 // We want to insert `ty` with no obligations. If the existing value
1657 // already has no obligations (as is common) we don't insert anything.
1658 if !ty.obligations.is_empty() {
1661 ProjectionCacheEntry::NormalizedTy(Normalized {
1663 obligations: vec![],
1669 /// Indicates that trying to normalize `key` resulted in
1670 /// ambiguity. No point in trying it again then until we gain more
1671 /// type information (in which case, the "fully resolved" key will
1673 fn ambiguous(&mut self, key: ProjectionCacheKey<'tcx>) {
1674 let fresh = self.map.insert(key, ProjectionCacheEntry::Ambiguous);
1675 assert!(!fresh, "never started projecting `{:?}`", key);
1678 /// Indicates that trying to normalize `key` resulted in
1680 fn error(&mut self, key: ProjectionCacheKey<'tcx>) {
1681 let fresh = self.map.insert(key, ProjectionCacheEntry::Error);
1682 assert!(!fresh, "never started projecting `{:?}`", key);