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 crate::ty::fold::{TypeFoldable, TypeFolder};
18 use crate::ty::subst::{InternalSubsts, Subst};
19 use crate::ty::{self, ToPolyTraitRef, ToPredicate, Ty, TyCtxt};
20 use rustc_data_structures::snapshot_map::{Snapshot, SnapshotMap};
21 use rustc_hir::def_id::DefId;
22 use rustc_macros::HashStable;
23 use rustc_span::symbol::sym;
24 use rustc_span::DUMMY_SP;
25 use syntax::ast::Ident;
27 /// Depending on the stage of compilation, we want projection to be
28 /// more or less conservative.
29 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, HashStable)]
31 /// At type-checking time, we refuse to project any associated
32 /// type that is marked `default`. Non-`default` ("final") types
33 /// are always projected. This is necessary in general for
34 /// soundness of specialization. However, we *could* allow
35 /// projections in fully-monomorphic cases. We choose not to,
36 /// because we prefer for `default type` to force the type
37 /// definition to be treated abstractly by any consumers of the
38 /// impl. Concretely, that means that the following example will
46 /// impl<T> Assoc for T {
47 /// default type Output = bool;
51 /// let <() as Assoc>::Output = true;
55 /// At codegen time, all monomorphic projections will succeed.
56 /// Also, `impl Trait` is normalized to the concrete type,
57 /// which has to be already collected by type-checking.
59 /// NOTE: as `impl Trait`'s concrete type should *never*
60 /// be observable directly by the user, `Reveal::All`
61 /// should not be used by checks which may expose
62 /// type equality or type contents to the user.
63 /// There are some exceptions, e.g., around OIBITS and
64 /// transmute-checking, which expose some details, but
65 /// not the whole concrete type of the `impl Trait`.
69 pub type PolyProjectionObligation<'tcx> = Obligation<'tcx, ty::PolyProjectionPredicate<'tcx>>;
71 pub type ProjectionObligation<'tcx> = Obligation<'tcx, ty::ProjectionPredicate<'tcx>>;
73 pub type ProjectionTyObligation<'tcx> = Obligation<'tcx, ty::ProjectionTy<'tcx>>;
75 /// When attempting to resolve `<T as TraitRef>::Name` ...
77 pub enum ProjectionTyError<'tcx> {
78 /// ...we found multiple sources of information and couldn't resolve the ambiguity.
81 /// ...an error occurred matching `T : TraitRef`
82 TraitSelectionError(SelectionError<'tcx>),
86 pub struct MismatchedProjectionTypes<'tcx> {
87 pub err: ty::error::TypeError<'tcx>,
90 #[derive(PartialEq, Eq, Debug)]
91 enum ProjectionTyCandidate<'tcx> {
92 // from a where-clause in the env or object type
93 ParamEnv(ty::PolyProjectionPredicate<'tcx>),
95 // from the definition of `Trait` when you have something like <<A as Trait>::B as Trait2>::C
96 TraitDef(ty::PolyProjectionPredicate<'tcx>),
98 // from a "impl" (or a "pseudo-impl" returned by select)
99 Select(Selection<'tcx>),
102 enum ProjectionTyCandidateSet<'tcx> {
104 Single(ProjectionTyCandidate<'tcx>),
106 Error(SelectionError<'tcx>),
109 impl<'tcx> ProjectionTyCandidateSet<'tcx> {
110 fn mark_ambiguous(&mut self) {
111 *self = ProjectionTyCandidateSet::Ambiguous;
114 fn mark_error(&mut self, err: SelectionError<'tcx>) {
115 *self = ProjectionTyCandidateSet::Error(err);
118 // Returns true if the push was successful, or false if the candidate
119 // was discarded -- this could be because of ambiguity, or because
120 // a higher-priority candidate is already there.
121 fn push_candidate(&mut self, candidate: ProjectionTyCandidate<'tcx>) -> bool {
122 use self::ProjectionTyCandidate::*;
123 use self::ProjectionTyCandidateSet::*;
125 // This wacky variable is just used to try and
126 // make code readable and avoid confusing paths.
127 // It is assigned a "value" of `()` only on those
128 // paths in which we wish to convert `*self` to
129 // ambiguous (and return false, because the candidate
130 // was not used). On other paths, it is not assigned,
131 // and hence if those paths *could* reach the code that
132 // comes after the match, this fn would not compile.
133 let convert_to_ambiguous;
137 *self = Single(candidate);
142 // Duplicates can happen inside ParamEnv. In the case, we
143 // perform a lazy deduplication.
144 if current == &candidate {
148 // Prefer where-clauses. As in select, if there are multiple
149 // candidates, we prefer where-clause candidates over impls. This
150 // may seem a bit surprising, since impls are the source of
151 // "truth" in some sense, but in fact some of the impls that SEEM
152 // applicable are not, because of nested obligations. Where
153 // clauses are the safer choice. See the comment on
154 // `select::SelectionCandidate` and #21974 for more details.
155 match (current, candidate) {
156 (ParamEnv(..), ParamEnv(..)) => convert_to_ambiguous = (),
157 (ParamEnv(..), _) => return false,
158 (_, ParamEnv(..)) => unreachable!(),
159 (_, _) => convert_to_ambiguous = (),
163 Ambiguous | Error(..) => {
168 // We only ever get here when we moved from a single candidate
170 let () = convert_to_ambiguous;
176 /// Evaluates constraints of the form:
178 /// for<...> <T as Trait>::U == V
180 /// If successful, this may result in additional obligations. Also returns
181 /// the projection cache key used to track these additional obligations.
182 pub fn poly_project_and_unify_type<'cx, 'tcx>(
183 selcx: &mut SelectionContext<'cx, 'tcx>,
184 obligation: &PolyProjectionObligation<'tcx>,
185 ) -> Result<Option<Vec<PredicateObligation<'tcx>>>, MismatchedProjectionTypes<'tcx>> {
186 debug!("poly_project_and_unify_type(obligation={:?})", obligation);
188 let infcx = selcx.infcx();
189 infcx.commit_if_ok(|snapshot| {
190 let (placeholder_predicate, placeholder_map) =
191 infcx.replace_bound_vars_with_placeholders(&obligation.predicate);
193 let placeholder_obligation = obligation.with(placeholder_predicate);
194 let result = project_and_unify_type(selcx, &placeholder_obligation)?;
196 .leak_check(false, &placeholder_map, snapshot)
197 .map_err(|err| MismatchedProjectionTypes { err })?;
202 /// Evaluates constraints of the form:
204 /// <T as Trait>::U == V
206 /// If successful, this may result in additional obligations.
207 fn project_and_unify_type<'cx, 'tcx>(
208 selcx: &mut SelectionContext<'cx, 'tcx>,
209 obligation: &ProjectionObligation<'tcx>,
210 ) -> Result<Option<Vec<PredicateObligation<'tcx>>>, MismatchedProjectionTypes<'tcx>> {
211 debug!("project_and_unify_type(obligation={:?})", obligation);
213 let mut obligations = vec![];
214 let normalized_ty = match opt_normalize_projection_type(
216 obligation.param_env,
217 obligation.predicate.projection_ty,
218 obligation.cause.clone(),
219 obligation.recursion_depth,
223 None => return Ok(None),
227 "project_and_unify_type: normalized_ty={:?} obligations={:?}",
228 normalized_ty, obligations
231 let infcx = selcx.infcx();
233 .at(&obligation.cause, obligation.param_env)
234 .eq(normalized_ty, obligation.predicate.ty)
236 Ok(InferOk { obligations: inferred_obligations, value: () }) => {
237 obligations.extend(inferred_obligations);
238 Ok(Some(obligations))
241 debug!("project_and_unify_type: equating types encountered error {:?}", err);
242 Err(MismatchedProjectionTypes { err })
247 /// Normalizes any associated type projections in `value`, replacing
248 /// them with a fully resolved type where possible. The return value
249 /// combines the normalized result and any additional obligations that
250 /// were incurred as result.
251 pub fn normalize<'a, 'b, 'tcx, T>(
252 selcx: &'a mut SelectionContext<'b, 'tcx>,
253 param_env: ty::ParamEnv<'tcx>,
254 cause: ObligationCause<'tcx>,
256 ) -> Normalized<'tcx, T>
258 T: TypeFoldable<'tcx>,
260 normalize_with_depth(selcx, param_env, cause, 0, value)
263 /// As `normalize`, but with a custom depth.
264 pub fn normalize_with_depth<'a, 'b, 'tcx, T>(
265 selcx: &'a mut SelectionContext<'b, 'tcx>,
266 param_env: ty::ParamEnv<'tcx>,
267 cause: ObligationCause<'tcx>,
270 ) -> Normalized<'tcx, T>
272 T: TypeFoldable<'tcx>,
274 debug!("normalize_with_depth(depth={}, value={:?})", depth, value);
275 let mut normalizer = AssocTypeNormalizer::new(selcx, param_env, cause, depth);
276 let result = normalizer.fold(value);
278 "normalize_with_depth: depth={} result={:?} with {} obligations",
281 normalizer.obligations.len()
283 debug!("normalize_with_depth: depth={} obligations={:?}", depth, normalizer.obligations);
284 Normalized { value: result, obligations: normalizer.obligations }
287 struct AssocTypeNormalizer<'a, 'b, 'tcx> {
288 selcx: &'a mut SelectionContext<'b, 'tcx>,
289 param_env: ty::ParamEnv<'tcx>,
290 cause: ObligationCause<'tcx>,
291 obligations: Vec<PredicateObligation<'tcx>>,
295 impl<'a, 'b, 'tcx> AssocTypeNormalizer<'a, 'b, 'tcx> {
297 selcx: &'a mut SelectionContext<'b, 'tcx>,
298 param_env: ty::ParamEnv<'tcx>,
299 cause: ObligationCause<'tcx>,
301 ) -> AssocTypeNormalizer<'a, 'b, 'tcx> {
302 AssocTypeNormalizer { selcx, param_env, cause, obligations: vec![], depth }
305 fn fold<T: TypeFoldable<'tcx>>(&mut self, value: &T) -> T {
306 let value = self.selcx.infcx().resolve_vars_if_possible(value);
308 if !value.has_projections() { value } else { value.fold_with(self) }
312 impl<'a, 'b, 'tcx> TypeFolder<'tcx> for AssocTypeNormalizer<'a, 'b, 'tcx> {
313 fn tcx<'c>(&'c self) -> TyCtxt<'tcx> {
317 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
318 if !ty.has_projections() {
321 // We don't want to normalize associated types that occur inside of region
322 // binders, because they may contain bound regions, and we can't cope with that.
326 // for<'a> fn(<T as Foo<&'a>>::A)
328 // Instead of normalizing `<T as Foo<&'a>>::A` here, we'll
329 // normalize it when we instantiate those bound regions (which
330 // should occur eventually).
332 let ty = ty.super_fold_with(self);
334 ty::Opaque(def_id, substs) if !substs.has_escaping_bound_vars() => {
336 // Only normalize `impl Trait` after type-checking, usually in codegen.
337 match self.param_env.reveal {
338 Reveal::UserFacing => ty,
341 let recursion_limit = *self.tcx().sess.recursion_limit.get();
342 if self.depth >= recursion_limit {
343 let obligation = Obligation::with_depth(
349 self.selcx.infcx().report_overflow_error(&obligation, true);
352 let generic_ty = self.tcx().type_of(def_id);
353 let concrete_ty = generic_ty.subst(self.tcx(), substs);
355 let folded_ty = self.fold_ty(concrete_ty);
362 ty::Projection(ref data) if !data.has_escaping_bound_vars() => {
365 // (*) This is kind of hacky -- we need to be able to
366 // handle normalization within binders because
367 // otherwise we wind up a need to normalize when doing
368 // trait matching (since you can have a trait
369 // obligation like `for<'a> T::B : Fn(&'a int)`), but
370 // we can't normalize with bound regions in scope. So
371 // far now we just ignore binders but only normalize
372 // if all bound regions are gone (and then we still
373 // have to renormalize whenever we instantiate a
374 // binder). It would be better to normalize in a
375 // binding-aware fashion.
377 let normalized_ty = normalize_projection_type(
383 &mut self.obligations,
386 "AssocTypeNormalizer: depth={} normalized {:?} to {:?}, \
387 now with {} obligations",
391 self.obligations.len()
400 fn fold_const(&mut self, constant: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
401 constant.eval(self.selcx.tcx(), self.param_env)
405 #[derive(Clone, TypeFoldable)]
406 pub struct Normalized<'tcx, T> {
408 pub obligations: Vec<PredicateObligation<'tcx>>,
411 pub type NormalizedTy<'tcx> = Normalized<'tcx, Ty<'tcx>>;
413 impl<'tcx, T> Normalized<'tcx, T> {
414 pub fn with<U>(self, value: U) -> Normalized<'tcx, U> {
415 Normalized { value: value, obligations: self.obligations }
419 /// The guts of `normalize`: normalize a specific projection like `<T
420 /// as Trait>::Item`. The result is always a type (and possibly
421 /// additional obligations). If ambiguity arises, which implies that
422 /// there are unresolved type variables in the projection, we will
423 /// substitute a fresh type variable `$X` and generate a new
424 /// obligation `<T as Trait>::Item == $X` for later.
425 pub fn normalize_projection_type<'a, 'b, 'tcx>(
426 selcx: &'a mut SelectionContext<'b, 'tcx>,
427 param_env: ty::ParamEnv<'tcx>,
428 projection_ty: ty::ProjectionTy<'tcx>,
429 cause: ObligationCause<'tcx>,
431 obligations: &mut Vec<PredicateObligation<'tcx>>,
433 opt_normalize_projection_type(
436 projection_ty.clone(),
441 .unwrap_or_else(move || {
442 // if we bottom out in ambiguity, create a type variable
443 // and a deferred predicate to resolve this when more type
444 // information is available.
446 let tcx = selcx.infcx().tcx;
447 let def_id = projection_ty.item_def_id;
448 let ty_var = selcx.infcx().next_ty_var(TypeVariableOrigin {
449 kind: TypeVariableOriginKind::NormalizeProjectionType,
450 span: tcx.def_span(def_id),
452 let projection = ty::Binder::dummy(ty::ProjectionPredicate { projection_ty, ty: ty_var });
454 Obligation::with_depth(cause, depth + 1, param_env, projection.to_predicate());
455 obligations.push(obligation);
460 /// The guts of `normalize`: normalize a specific projection like `<T
461 /// as Trait>::Item`. The result is always a type (and possibly
462 /// additional obligations). Returns `None` in the case of ambiguity,
463 /// which indicates that there are unbound type variables.
465 /// This function used to return `Option<NormalizedTy<'tcx>>`, which contains a
466 /// `Ty<'tcx>` and an obligations vector. But that obligation vector was very
467 /// often immediately appended to another obligations vector. So now this
468 /// function takes an obligations vector and appends to it directly, which is
469 /// slightly uglier but avoids the need for an extra short-lived allocation.
470 fn opt_normalize_projection_type<'a, 'b, 'tcx>(
471 selcx: &'a mut SelectionContext<'b, 'tcx>,
472 param_env: ty::ParamEnv<'tcx>,
473 projection_ty: ty::ProjectionTy<'tcx>,
474 cause: ObligationCause<'tcx>,
476 obligations: &mut Vec<PredicateObligation<'tcx>>,
477 ) -> Option<Ty<'tcx>> {
478 let infcx = selcx.infcx();
480 let projection_ty = infcx.resolve_vars_if_possible(&projection_ty);
481 let cache_key = ProjectionCacheKey { ty: projection_ty };
484 "opt_normalize_projection_type(\
485 projection_ty={:?}, \
490 // FIXME(#20304) For now, I am caching here, which is good, but it
491 // means we don't capture the type variables that are created in
492 // the case of ambiguity. Which means we may create a large stream
493 // of such variables. OTOH, if we move the caching up a level, we
494 // would not benefit from caching when proving `T: Trait<U=Foo>`
495 // bounds. It might be the case that we want two distinct caches,
496 // or else another kind of cache entry.
498 let cache_result = infcx.projection_cache.borrow_mut().try_start(cache_key);
501 Err(ProjectionCacheEntry::Ambiguous) => {
502 // If we found ambiguity the last time, that generally
503 // means we will continue to do so until some type in the
504 // key changes (and we know it hasn't, because we just
505 // fully resolved it). One exception though is closure
506 // types, which can transition from having a fixed kind to
507 // no kind with no visible change in the key.
509 // FIXME(#32286) refactor this so that closure type
512 "opt_normalize_projection_type: \
513 found cache entry: ambiguous"
515 if !projection_ty.has_closure_types() {
519 Err(ProjectionCacheEntry::InProgress) => {
520 // If while normalized A::B, we are asked to normalize
521 // A::B, just return A::B itself. This is a conservative
522 // answer, in the sense that A::B *is* clearly equivalent
523 // to A::B, though there may be a better value we can
526 // Under lazy normalization, this can arise when
527 // bootstrapping. That is, imagine an environment with a
528 // where-clause like `A::B == u32`. Now, if we are asked
529 // to normalize `A::B`, we will want to check the
530 // where-clauses in scope. So we will try to unify `A::B`
531 // with `A::B`, which can trigger a recursive
532 // normalization. In that case, I think we will want this code:
535 // let ty = selcx.tcx().mk_projection(projection_ty.item_def_id,
536 // projection_ty.substs;
537 // return Some(NormalizedTy { value: v, obligations: vec![] });
541 "opt_normalize_projection_type: \
542 found cache entry: in-progress"
545 // But for now, let's classify this as an overflow:
546 let recursion_limit = *selcx.tcx().sess.recursion_limit.get();
548 Obligation::with_depth(cause, recursion_limit, param_env, projection_ty);
549 selcx.infcx().report_overflow_error(&obligation, false);
551 Err(ProjectionCacheEntry::NormalizedTy(ty)) => {
552 // This is the hottest path in this function.
554 // If we find the value in the cache, then return it along
555 // with the obligations that went along with it. Note
556 // that, when using a fulfillment context, these
557 // obligations could in principle be ignored: they have
558 // already been registered when the cache entry was
559 // created (and hence the new ones will quickly be
560 // discarded as duplicated). But when doing trait
561 // evaluation this is not the case, and dropping the trait
562 // evaluations can causes ICEs (e.g., #43132).
564 "opt_normalize_projection_type: \
565 found normalized ty `{:?}`",
569 // Once we have inferred everything we need to know, we
570 // can ignore the `obligations` from that point on.
571 if infcx.unresolved_type_vars(&ty.value).is_none() {
572 infcx.projection_cache.borrow_mut().complete_normalized(cache_key, &ty);
573 // No need to extend `obligations`.
575 obligations.extend(ty.obligations);
578 obligations.push(get_paranoid_cache_value_obligation(
585 return Some(ty.value);
587 Err(ProjectionCacheEntry::Error) => {
589 "opt_normalize_projection_type: \
592 let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth);
593 obligations.extend(result.obligations);
594 return Some(result.value);
598 let obligation = Obligation::with_depth(cause.clone(), depth, param_env, projection_ty);
599 match project_type(selcx, &obligation) {
600 Ok(ProjectedTy::Progress(Progress {
602 obligations: mut projected_obligations,
604 // if projection succeeded, then what we get out of this
605 // is also non-normalized (consider: it was derived from
606 // an impl, where-clause etc) and hence we must
610 "opt_normalize_projection_type: \
613 projected_obligations={:?}",
614 projected_ty, depth, projected_obligations
617 let result = if projected_ty.has_projections() {
618 let mut normalizer = AssocTypeNormalizer::new(selcx, param_env, cause, depth + 1);
619 let normalized_ty = normalizer.fold(&projected_ty);
622 "opt_normalize_projection_type: \
623 normalized_ty={:?} depth={}",
627 projected_obligations.extend(normalizer.obligations);
628 Normalized { value: normalized_ty, obligations: projected_obligations }
630 Normalized { value: projected_ty, obligations: projected_obligations }
633 let cache_value = prune_cache_value_obligations(infcx, &result);
634 infcx.projection_cache.borrow_mut().insert_ty(cache_key, cache_value);
635 obligations.extend(result.obligations);
638 Ok(ProjectedTy::NoProgress(projected_ty)) => {
640 "opt_normalize_projection_type: \
641 projected_ty={:?} no progress",
644 let result = Normalized { value: projected_ty, obligations: vec![] };
645 infcx.projection_cache.borrow_mut().insert_ty(cache_key, result.clone());
646 // No need to extend `obligations`.
649 Err(ProjectionTyError::TooManyCandidates) => {
651 "opt_normalize_projection_type: \
654 infcx.projection_cache.borrow_mut().ambiguous(cache_key);
657 Err(ProjectionTyError::TraitSelectionError(_)) => {
658 debug!("opt_normalize_projection_type: ERROR");
659 // if we got an error processing the `T as Trait` part,
660 // just return `ty::err` but add the obligation `T :
661 // Trait`, which when processed will cause the error to be
664 infcx.projection_cache.borrow_mut().error(cache_key);
665 let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth);
666 obligations.extend(result.obligations);
672 /// If there are unresolved type variables, then we need to include
673 /// any subobligations that bind them, at least until those type
674 /// variables are fully resolved.
675 fn prune_cache_value_obligations<'a, 'tcx>(
676 infcx: &'a InferCtxt<'a, 'tcx>,
677 result: &NormalizedTy<'tcx>,
678 ) -> NormalizedTy<'tcx> {
679 if infcx.unresolved_type_vars(&result.value).is_none() {
680 return NormalizedTy { value: result.value, obligations: vec![] };
683 let mut obligations: Vec<_> = result
686 .filter(|obligation| match obligation.predicate {
687 // We found a `T: Foo<X = U>` predicate, let's check
688 // if `U` references any unresolved type
689 // variables. In principle, we only care if this
690 // projection can help resolve any of the type
691 // variables found in `result.value` -- but we just
692 // check for any type variables here, for fear of
693 // indirect obligations (e.g., we project to `?0`,
694 // but we have `T: Foo<X = ?1>` and `?1: Bar<X =
696 ty::Predicate::Projection(ref data) => infcx.unresolved_type_vars(&data.ty()).is_some(),
698 // We are only interested in `T: Foo<X = U>` predicates, whre
699 // `U` references one of `unresolved_type_vars`. =)
705 obligations.shrink_to_fit();
707 NormalizedTy { value: result.value, obligations }
710 /// Whenever we give back a cache result for a projection like `<T as
711 /// Trait>::Item ==> X`, we *always* include the obligation to prove
712 /// that `T: Trait` (we may also include some other obligations). This
713 /// may or may not be necessary -- in principle, all the obligations
714 /// that must be proven to show that `T: Trait` were also returned
715 /// when the cache was first populated. But there are some vague concerns,
716 /// and so we take the precautionary measure of including `T: Trait` in
719 /// Concern #1. The current setup is fragile. Perhaps someone could
720 /// have failed to prove the concerns from when the cache was
721 /// populated, but also not have used a snapshot, in which case the
722 /// cache could remain populated even though `T: Trait` has not been
723 /// shown. In this case, the "other code" is at fault -- when you
724 /// project something, you are supposed to either have a snapshot or
725 /// else prove all the resulting obligations -- but it's still easy to
728 /// Concern #2. Even within the snapshot, if those original
729 /// obligations are not yet proven, then we are able to do projections
730 /// that may yet turn out to be wrong. This *may* lead to some sort
731 /// of trouble, though we don't have a concrete example of how that
732 /// can occur yet. But it seems risky at best.
733 fn get_paranoid_cache_value_obligation<'a, 'tcx>(
734 infcx: &'a InferCtxt<'a, 'tcx>,
735 param_env: ty::ParamEnv<'tcx>,
736 projection_ty: ty::ProjectionTy<'tcx>,
737 cause: ObligationCause<'tcx>,
739 ) -> PredicateObligation<'tcx> {
740 let trait_ref = projection_ty.trait_ref(infcx.tcx).to_poly_trait_ref();
741 Obligation { cause, recursion_depth: depth, param_env, predicate: trait_ref.to_predicate() }
744 /// If we are projecting `<T as Trait>::Item`, but `T: Trait` does not
745 /// hold. In various error cases, we cannot generate a valid
746 /// normalized projection. Therefore, we create an inference variable
747 /// return an associated obligation that, when fulfilled, will lead to
750 /// Note that we used to return `Error` here, but that was quite
751 /// dubious -- the premise was that an error would *eventually* be
752 /// reported, when the obligation was processed. But in general once
753 /// you see a `Error` you are supposed to be able to assume that an
754 /// error *has been* reported, so that you can take whatever heuristic
755 /// paths you want to take. To make things worse, it was possible for
756 /// cycles to arise, where you basically had a setup like `<MyType<$0>
757 /// as Trait>::Foo == $0`. Here, normalizing `<MyType<$0> as
758 /// Trait>::Foo> to `[type error]` would lead to an obligation of
759 /// `<MyType<[type error]> as Trait>::Foo`. We are supposed to report
760 /// an error for this obligation, but we legitimately should not,
761 /// because it contains `[type error]`. Yuck! (See issue #29857 for
762 /// one case where this arose.)
763 fn normalize_to_error<'a, 'tcx>(
764 selcx: &mut SelectionContext<'a, 'tcx>,
765 param_env: ty::ParamEnv<'tcx>,
766 projection_ty: ty::ProjectionTy<'tcx>,
767 cause: ObligationCause<'tcx>,
769 ) -> NormalizedTy<'tcx> {
770 let trait_ref = projection_ty.trait_ref(selcx.tcx()).to_poly_trait_ref();
771 let trait_obligation = Obligation {
773 recursion_depth: depth,
775 predicate: trait_ref.to_predicate(),
777 let tcx = selcx.infcx().tcx;
778 let def_id = projection_ty.item_def_id;
779 let new_value = selcx.infcx().next_ty_var(TypeVariableOrigin {
780 kind: TypeVariableOriginKind::NormalizeProjectionType,
781 span: tcx.def_span(def_id),
783 Normalized { value: new_value, obligations: vec![trait_obligation] }
786 enum ProjectedTy<'tcx> {
787 Progress(Progress<'tcx>),
788 NoProgress(Ty<'tcx>),
791 struct Progress<'tcx> {
793 obligations: Vec<PredicateObligation<'tcx>>,
796 impl<'tcx> Progress<'tcx> {
797 fn error(tcx: TyCtxt<'tcx>) -> Self {
798 Progress { ty: tcx.types.err, obligations: vec![] }
801 fn with_addl_obligations(mut self, mut obligations: Vec<PredicateObligation<'tcx>>) -> Self {
803 "with_addl_obligations: self.obligations.len={} obligations.len={}",
804 self.obligations.len(),
809 "with_addl_obligations: self.obligations={:?} obligations={:?}",
810 self.obligations, obligations
813 self.obligations.append(&mut obligations);
818 /// Computes the result of a projection type (if we can).
821 /// - `obligation` must be fully normalized
822 fn project_type<'cx, 'tcx>(
823 selcx: &mut SelectionContext<'cx, 'tcx>,
824 obligation: &ProjectionTyObligation<'tcx>,
825 ) -> Result<ProjectedTy<'tcx>, ProjectionTyError<'tcx>> {
826 debug!("project(obligation={:?})", obligation);
828 let recursion_limit = *selcx.tcx().sess.recursion_limit.get();
829 if obligation.recursion_depth >= recursion_limit {
830 debug!("project: overflow!");
831 return Err(ProjectionTyError::TraitSelectionError(SelectionError::Overflow));
834 let obligation_trait_ref = &obligation.predicate.trait_ref(selcx.tcx());
836 debug!("project: obligation_trait_ref={:?}", obligation_trait_ref);
838 if obligation_trait_ref.references_error() {
839 return Ok(ProjectedTy::Progress(Progress::error(selcx.tcx())));
842 let mut candidates = ProjectionTyCandidateSet::None;
844 // Make sure that the following procedures are kept in order. ParamEnv
845 // needs to be first because it has highest priority, and Select checks
846 // the return value of push_candidate which assumes it's ran at last.
847 assemble_candidates_from_param_env(selcx, obligation, &obligation_trait_ref, &mut candidates);
849 assemble_candidates_from_trait_def(selcx, obligation, &obligation_trait_ref, &mut candidates);
851 assemble_candidates_from_impls(selcx, obligation, &obligation_trait_ref, &mut candidates);
854 ProjectionTyCandidateSet::Single(candidate) => Ok(ProjectedTy::Progress(
855 confirm_candidate(selcx, obligation, &obligation_trait_ref, candidate),
857 ProjectionTyCandidateSet::None => Ok(ProjectedTy::NoProgress(
860 .mk_projection(obligation.predicate.item_def_id, obligation.predicate.substs),
862 // Error occurred while trying to processing impls.
863 ProjectionTyCandidateSet::Error(e) => Err(ProjectionTyError::TraitSelectionError(e)),
864 // Inherent ambiguity that prevents us from even enumerating the
866 ProjectionTyCandidateSet::Ambiguous => Err(ProjectionTyError::TooManyCandidates),
870 /// The first thing we have to do is scan through the parameter
871 /// environment to see whether there are any projection predicates
872 /// there that can answer this question.
873 fn assemble_candidates_from_param_env<'cx, 'tcx>(
874 selcx: &mut SelectionContext<'cx, 'tcx>,
875 obligation: &ProjectionTyObligation<'tcx>,
876 obligation_trait_ref: &ty::TraitRef<'tcx>,
877 candidate_set: &mut ProjectionTyCandidateSet<'tcx>,
879 debug!("assemble_candidates_from_param_env(..)");
880 assemble_candidates_from_predicates(
883 obligation_trait_ref,
885 ProjectionTyCandidate::ParamEnv,
886 obligation.param_env.caller_bounds.iter().cloned(),
890 /// In the case of a nested projection like <<A as Foo>::FooT as Bar>::BarT, we may find
891 /// that the definition of `Foo` has some clues:
895 /// type FooT : Bar<BarT=i32>
899 /// Here, for example, we could conclude that the result is `i32`.
900 fn assemble_candidates_from_trait_def<'cx, 'tcx>(
901 selcx: &mut SelectionContext<'cx, 'tcx>,
902 obligation: &ProjectionTyObligation<'tcx>,
903 obligation_trait_ref: &ty::TraitRef<'tcx>,
904 candidate_set: &mut ProjectionTyCandidateSet<'tcx>,
906 debug!("assemble_candidates_from_trait_def(..)");
908 let tcx = selcx.tcx();
909 // Check whether the self-type is itself a projection.
910 let (def_id, substs) = match obligation_trait_ref.self_ty().kind {
911 ty::Projection(ref data) => (data.trait_ref(tcx).def_id, data.substs),
912 ty::Opaque(def_id, substs) => (def_id, substs),
913 ty::Infer(ty::TyVar(_)) => {
914 // If the self-type is an inference variable, then it MAY wind up
915 // being a projected type, so induce an ambiguity.
916 candidate_set.mark_ambiguous();
922 // If so, extract what we know from the trait and try to come up with a good answer.
923 let trait_predicates = tcx.predicates_of(def_id);
924 let bounds = trait_predicates.instantiate(tcx, substs);
925 let bounds = elaborate_predicates(tcx, bounds.predicates);
926 assemble_candidates_from_predicates(
929 obligation_trait_ref,
931 ProjectionTyCandidate::TraitDef,
936 fn assemble_candidates_from_predicates<'cx, 'tcx, I>(
937 selcx: &mut SelectionContext<'cx, 'tcx>,
938 obligation: &ProjectionTyObligation<'tcx>,
939 obligation_trait_ref: &ty::TraitRef<'tcx>,
940 candidate_set: &mut ProjectionTyCandidateSet<'tcx>,
941 ctor: fn(ty::PolyProjectionPredicate<'tcx>) -> ProjectionTyCandidate<'tcx>,
944 I: IntoIterator<Item = ty::Predicate<'tcx>>,
946 debug!("assemble_candidates_from_predicates(obligation={:?})", obligation);
947 let infcx = selcx.infcx();
948 for predicate in env_predicates {
949 debug!("assemble_candidates_from_predicates: predicate={:?}", predicate);
950 if let ty::Predicate::Projection(data) = predicate {
951 let same_def_id = data.projection_def_id() == obligation.predicate.item_def_id;
953 let is_match = same_def_id
955 let data_poly_trait_ref = data.to_poly_trait_ref(infcx.tcx);
956 let obligation_poly_trait_ref = obligation_trait_ref.to_poly_trait_ref();
958 .at(&obligation.cause, obligation.param_env)
959 .sup(obligation_poly_trait_ref, data_poly_trait_ref)
960 .map(|InferOk { obligations: _, value: () }| {
961 // FIXME(#32730) -- do we need to take obligations
962 // into account in any way? At the moment, no.
968 "assemble_candidates_from_predicates: candidate={:?} \
969 is_match={} same_def_id={}",
970 data, is_match, same_def_id
974 candidate_set.push_candidate(ctor(data));
980 fn assemble_candidates_from_impls<'cx, 'tcx>(
981 selcx: &mut SelectionContext<'cx, 'tcx>,
982 obligation: &ProjectionTyObligation<'tcx>,
983 obligation_trait_ref: &ty::TraitRef<'tcx>,
984 candidate_set: &mut ProjectionTyCandidateSet<'tcx>,
986 // If we are resolving `<T as TraitRef<...>>::Item == Type`,
987 // start out by selecting the predicate `T as TraitRef<...>`:
988 let poly_trait_ref = obligation_trait_ref.to_poly_trait_ref();
989 let trait_obligation = obligation.with(poly_trait_ref.to_poly_trait_predicate());
990 let _ = selcx.infcx().commit_if_ok(|_| {
991 let vtable = match selcx.select(&trait_obligation) {
992 Ok(Some(vtable)) => vtable,
994 candidate_set.mark_ambiguous();
998 debug!("assemble_candidates_from_impls: selection error {:?}", e);
999 candidate_set.mark_error(e);
1004 let eligible = match &vtable {
1005 super::VtableClosure(_)
1006 | super::VtableGenerator(_)
1007 | super::VtableFnPointer(_)
1008 | super::VtableObject(_)
1009 | super::VtableTraitAlias(_) => {
1010 debug!("assemble_candidates_from_impls: vtable={:?}", vtable);
1013 super::VtableImpl(impl_data) => {
1014 // We have to be careful when projecting out of an
1015 // impl because of specialization. If we are not in
1016 // codegen (i.e., projection mode is not "any"), and the
1017 // impl's type is declared as default, then we disable
1018 // projection (even if the trait ref is fully
1019 // monomorphic). In the case where trait ref is not
1020 // fully monomorphic (i.e., includes type parameters),
1021 // this is because those type parameters may
1022 // ultimately be bound to types from other crates that
1023 // may have specialized impls we can't see. In the
1024 // case where the trait ref IS fully monomorphic, this
1025 // is a policy decision that we made in the RFC in
1026 // order to preserve flexibility for the crate that
1027 // defined the specializable impl to specialize later
1028 // for existing types.
1030 // In either case, we handle this by not adding a
1031 // candidate for an impl if it contains a `default`
1034 // NOTE: This should be kept in sync with the similar code in
1035 // `rustc::ty::instance::resolve_associated_item()`.
1037 assoc_ty_def(selcx, impl_data.impl_def_id, obligation.predicate.item_def_id);
1039 let is_default = if node_item.node.is_from_trait() {
1040 // If true, the impl inherited a `type Foo = Bar`
1041 // given in the trait, which is implicitly default.
1042 // Otherwise, the impl did not specify `type` and
1043 // neither did the trait:
1046 // trait Foo { type T; }
1047 // impl Foo for Bar { }
1050 // This is an error, but it will be
1051 // reported in `check_impl_items_against_trait`.
1052 // We accept it here but will flag it as
1053 // an error when we confirm the candidate
1054 // (which will ultimately lead to `normalize_to_error`
1056 node_item.item.defaultness.has_value()
1058 node_item.item.defaultness.is_default()
1059 || super::util::impl_is_default(selcx.tcx(), node_item.node.def_id())
1062 // Only reveal a specializable default if we're past type-checking
1063 // and the obligations is monomorphic, otherwise passes such as
1064 // transmute checking and polymorphic MIR optimizations could
1065 // get a result which isn't correct for all monomorphizations.
1068 } else if obligation.param_env.reveal == Reveal::All {
1069 // NOTE(eddyb) inference variables can resolve to parameters, so
1070 // assume `poly_trait_ref` isn't monomorphic, if it contains any.
1071 let poly_trait_ref = selcx.infcx().resolve_vars_if_possible(&poly_trait_ref);
1072 !poly_trait_ref.needs_infer() && !poly_trait_ref.needs_subst()
1077 super::VtableParam(..) => {
1078 // This case tell us nothing about the value of an
1079 // associated type. Consider:
1082 // trait SomeTrait { type Foo; }
1083 // fn foo<T:SomeTrait>(...) { }
1086 // If the user writes `<T as SomeTrait>::Foo`, then the `T
1087 // : SomeTrait` binding does not help us decide what the
1088 // type `Foo` is (at least, not more specifically than
1089 // what we already knew).
1091 // But wait, you say! What about an example like this:
1094 // fn bar<T:SomeTrait<Foo=usize>>(...) { ... }
1097 // Doesn't the `T : Sometrait<Foo=usize>` predicate help
1098 // resolve `T::Foo`? And of course it does, but in fact
1099 // that single predicate is desugared into two predicates
1100 // in the compiler: a trait predicate (`T : SomeTrait`) and a
1101 // projection. And the projection where clause is handled
1102 // in `assemble_candidates_from_param_env`.
1105 super::VtableAutoImpl(..) | super::VtableBuiltin(..) => {
1106 // These traits have no associated types.
1108 obligation.cause.span,
1109 "Cannot project an associated type from `{:?}`",
1116 if candidate_set.push_candidate(ProjectionTyCandidate::Select(vtable)) {
1127 fn confirm_candidate<'cx, 'tcx>(
1128 selcx: &mut SelectionContext<'cx, 'tcx>,
1129 obligation: &ProjectionTyObligation<'tcx>,
1130 obligation_trait_ref: &ty::TraitRef<'tcx>,
1131 candidate: ProjectionTyCandidate<'tcx>,
1132 ) -> Progress<'tcx> {
1133 debug!("confirm_candidate(candidate={:?}, obligation={:?})", candidate, obligation);
1136 ProjectionTyCandidate::ParamEnv(poly_projection)
1137 | ProjectionTyCandidate::TraitDef(poly_projection) => {
1138 confirm_param_env_candidate(selcx, obligation, poly_projection)
1141 ProjectionTyCandidate::Select(vtable) => {
1142 confirm_select_candidate(selcx, obligation, obligation_trait_ref, vtable)
1147 fn confirm_select_candidate<'cx, 'tcx>(
1148 selcx: &mut SelectionContext<'cx, 'tcx>,
1149 obligation: &ProjectionTyObligation<'tcx>,
1150 obligation_trait_ref: &ty::TraitRef<'tcx>,
1151 vtable: Selection<'tcx>,
1152 ) -> Progress<'tcx> {
1154 super::VtableImpl(data) => confirm_impl_candidate(selcx, obligation, data),
1155 super::VtableGenerator(data) => confirm_generator_candidate(selcx, obligation, data),
1156 super::VtableClosure(data) => confirm_closure_candidate(selcx, obligation, data),
1157 super::VtableFnPointer(data) => confirm_fn_pointer_candidate(selcx, obligation, data),
1158 super::VtableObject(_) => confirm_object_candidate(selcx, obligation, obligation_trait_ref),
1159 super::VtableAutoImpl(..)
1160 | super::VtableParam(..)
1161 | super::VtableBuiltin(..)
1162 | super::VtableTraitAlias(..) =>
1163 // we don't create Select candidates with this kind of resolution
1166 obligation.cause.span,
1167 "Cannot project an associated type from `{:?}`",
1174 fn confirm_object_candidate<'cx, 'tcx>(
1175 selcx: &mut SelectionContext<'cx, 'tcx>,
1176 obligation: &ProjectionTyObligation<'tcx>,
1177 obligation_trait_ref: &ty::TraitRef<'tcx>,
1178 ) -> Progress<'tcx> {
1179 let self_ty = obligation_trait_ref.self_ty();
1180 let object_ty = selcx.infcx().shallow_resolve(self_ty);
1181 debug!("confirm_object_candidate(object_ty={:?})", object_ty);
1182 let data = match object_ty.kind {
1183 ty::Dynamic(ref data, ..) => data,
1185 obligation.cause.span,
1186 "confirm_object_candidate called with non-object: {:?}",
1190 let env_predicates = data
1191 .projection_bounds()
1192 .map(|p| p.with_self_ty(selcx.tcx(), object_ty).to_predicate())
1194 let env_predicate = {
1195 let env_predicates = elaborate_predicates(selcx.tcx(), env_predicates);
1197 // select only those projections that are actually projecting an
1198 // item with the correct name
1199 let env_predicates = env_predicates.filter_map(|p| match p {
1200 ty::Predicate::Projection(data) => {
1201 if data.projection_def_id() == obligation.predicate.item_def_id {
1210 // select those with a relevant trait-ref
1211 let mut env_predicates = env_predicates.filter(|data| {
1212 let data_poly_trait_ref = data.to_poly_trait_ref(selcx.tcx());
1213 let obligation_poly_trait_ref = obligation_trait_ref.to_poly_trait_ref();
1214 selcx.infcx().probe(|_| {
1217 .at(&obligation.cause, obligation.param_env)
1218 .sup(obligation_poly_trait_ref, data_poly_trait_ref)
1223 // select the first matching one; there really ought to be one or
1224 // else the object type is not WF, since an object type should
1225 // include all of its projections explicitly
1226 match env_predicates.next() {
1227 Some(env_predicate) => env_predicate,
1230 "confirm_object_candidate: no env-predicate \
1231 found in object type `{:?}`; ill-formed",
1234 return Progress::error(selcx.tcx());
1239 confirm_param_env_candidate(selcx, obligation, env_predicate)
1242 fn confirm_generator_candidate<'cx, 'tcx>(
1243 selcx: &mut SelectionContext<'cx, 'tcx>,
1244 obligation: &ProjectionTyObligation<'tcx>,
1245 vtable: VtableGeneratorData<'tcx, PredicateObligation<'tcx>>,
1246 ) -> Progress<'tcx> {
1247 let gen_sig = vtable.substs.as_generator().poly_sig(vtable.generator_def_id, selcx.tcx());
1248 let Normalized { value: gen_sig, obligations } = normalize_with_depth(
1250 obligation.param_env,
1251 obligation.cause.clone(),
1252 obligation.recursion_depth + 1,
1257 "confirm_generator_candidate: obligation={:?},gen_sig={:?},obligations={:?}",
1258 obligation, gen_sig, obligations
1261 let tcx = selcx.tcx();
1263 let gen_def_id = tcx.lang_items().gen_trait().unwrap();
1265 let predicate = super::util::generator_trait_ref_and_outputs(
1268 obligation.predicate.self_ty(),
1271 .map_bound(|(trait_ref, yield_ty, return_ty)| {
1272 let name = tcx.associated_item(obligation.predicate.item_def_id).ident.name;
1273 let ty = if name == sym::Return {
1275 } else if name == sym::Yield {
1281 ty::ProjectionPredicate {
1282 projection_ty: ty::ProjectionTy {
1283 substs: trait_ref.substs,
1284 item_def_id: obligation.predicate.item_def_id,
1290 confirm_param_env_candidate(selcx, obligation, predicate)
1291 .with_addl_obligations(vtable.nested)
1292 .with_addl_obligations(obligations)
1295 fn confirm_fn_pointer_candidate<'cx, 'tcx>(
1296 selcx: &mut SelectionContext<'cx, 'tcx>,
1297 obligation: &ProjectionTyObligation<'tcx>,
1298 fn_pointer_vtable: VtableFnPointerData<'tcx, PredicateObligation<'tcx>>,
1299 ) -> Progress<'tcx> {
1300 let fn_type = selcx.infcx().shallow_resolve(fn_pointer_vtable.fn_ty);
1301 let sig = fn_type.fn_sig(selcx.tcx());
1302 let Normalized { value: sig, obligations } = normalize_with_depth(
1304 obligation.param_env,
1305 obligation.cause.clone(),
1306 obligation.recursion_depth + 1,
1310 confirm_callable_candidate(selcx, obligation, sig, util::TupleArgumentsFlag::Yes)
1311 .with_addl_obligations(fn_pointer_vtable.nested)
1312 .with_addl_obligations(obligations)
1315 fn confirm_closure_candidate<'cx, 'tcx>(
1316 selcx: &mut SelectionContext<'cx, 'tcx>,
1317 obligation: &ProjectionTyObligation<'tcx>,
1318 vtable: VtableClosureData<'tcx, PredicateObligation<'tcx>>,
1319 ) -> Progress<'tcx> {
1320 let tcx = selcx.tcx();
1321 let infcx = selcx.infcx();
1322 let closure_sig_ty = vtable.substs.as_closure().sig_ty(vtable.closure_def_id, tcx);
1323 let closure_sig = infcx.shallow_resolve(closure_sig_ty).fn_sig(tcx);
1324 let Normalized { value: closure_sig, obligations } = normalize_with_depth(
1326 obligation.param_env,
1327 obligation.cause.clone(),
1328 obligation.recursion_depth + 1,
1333 "confirm_closure_candidate: obligation={:?},closure_sig={:?},obligations={:?}",
1334 obligation, closure_sig, obligations
1337 confirm_callable_candidate(selcx, obligation, closure_sig, util::TupleArgumentsFlag::No)
1338 .with_addl_obligations(vtable.nested)
1339 .with_addl_obligations(obligations)
1342 fn confirm_callable_candidate<'cx, 'tcx>(
1343 selcx: &mut SelectionContext<'cx, 'tcx>,
1344 obligation: &ProjectionTyObligation<'tcx>,
1345 fn_sig: ty::PolyFnSig<'tcx>,
1346 flag: util::TupleArgumentsFlag,
1347 ) -> Progress<'tcx> {
1348 let tcx = selcx.tcx();
1350 debug!("confirm_callable_candidate({:?},{:?})", obligation, fn_sig);
1352 // the `Output` associated type is declared on `FnOnce`
1353 let fn_once_def_id = tcx.lang_items().fn_once_trait().unwrap();
1355 let predicate = super::util::closure_trait_ref_and_return_type(
1358 obligation.predicate.self_ty(),
1362 .map_bound(|(trait_ref, ret_type)| ty::ProjectionPredicate {
1363 projection_ty: ty::ProjectionTy::from_ref_and_name(
1366 Ident::with_dummy_span(rustc_hir::FN_OUTPUT_NAME),
1371 confirm_param_env_candidate(selcx, obligation, predicate)
1374 fn confirm_param_env_candidate<'cx, 'tcx>(
1375 selcx: &mut SelectionContext<'cx, 'tcx>,
1376 obligation: &ProjectionTyObligation<'tcx>,
1377 poly_cache_entry: ty::PolyProjectionPredicate<'tcx>,
1378 ) -> Progress<'tcx> {
1379 let infcx = selcx.infcx();
1380 let cause = &obligation.cause;
1381 let param_env = obligation.param_env;
1383 let (cache_entry, _) = infcx.replace_bound_vars_with_fresh_vars(
1385 LateBoundRegionConversionTime::HigherRankedType,
1389 let cache_trait_ref = cache_entry.projection_ty.trait_ref(infcx.tcx);
1390 let obligation_trait_ref = obligation.predicate.trait_ref(infcx.tcx);
1391 match infcx.at(cause, param_env).eq(cache_trait_ref, obligation_trait_ref) {
1392 Ok(InferOk { value: _, obligations }) => Progress { ty: cache_entry.ty, obligations },
1395 "Failed to unify obligation `{:?}` with poly_projection `{:?}`: {:?}",
1396 obligation, poly_cache_entry, e,
1398 debug!("confirm_param_env_candidate: {}", msg);
1399 infcx.tcx.sess.delay_span_bug(obligation.cause.span, &msg);
1400 Progress { ty: infcx.tcx.types.err, obligations: vec![] }
1405 fn confirm_impl_candidate<'cx, 'tcx>(
1406 selcx: &mut SelectionContext<'cx, 'tcx>,
1407 obligation: &ProjectionTyObligation<'tcx>,
1408 impl_vtable: VtableImplData<'tcx, PredicateObligation<'tcx>>,
1409 ) -> Progress<'tcx> {
1410 let tcx = selcx.tcx();
1412 let VtableImplData { impl_def_id, substs, nested } = impl_vtable;
1413 let assoc_item_id = obligation.predicate.item_def_id;
1414 let trait_def_id = tcx.trait_id_of_impl(impl_def_id).unwrap();
1416 let param_env = obligation.param_env;
1417 let assoc_ty = assoc_ty_def(selcx, impl_def_id, assoc_item_id);
1419 if !assoc_ty.item.defaultness.has_value() {
1420 // This means that the impl is missing a definition for the
1421 // associated type. This error will be reported by the type
1422 // checker method `check_impl_items_against_trait`, so here we
1423 // just return Error.
1425 "confirm_impl_candidate: no associated type {:?} for {:?}",
1426 assoc_ty.item.ident, obligation.predicate
1428 return Progress { ty: tcx.types.err, obligations: nested };
1430 let substs = obligation.predicate.substs.rebase_onto(tcx, trait_def_id, substs);
1431 let substs = translate_substs(selcx.infcx(), param_env, impl_def_id, substs, assoc_ty.node);
1432 let ty = if let ty::AssocKind::OpaqueTy = assoc_ty.item.kind {
1433 let item_substs = InternalSubsts::identity_for_item(tcx, assoc_ty.item.def_id);
1434 tcx.mk_opaque(assoc_ty.item.def_id, item_substs)
1436 tcx.type_of(assoc_ty.item.def_id)
1438 if substs.len() != tcx.generics_of(assoc_ty.item.def_id).count() {
1440 .delay_span_bug(DUMMY_SP, "impl item and trait item have different parameter counts");
1441 Progress { ty: tcx.types.err, obligations: nested }
1443 Progress { ty: ty.subst(tcx, substs), obligations: nested }
1447 /// Locate the definition of an associated type in the specialization hierarchy,
1448 /// starting from the given impl.
1450 /// Based on the "projection mode", this lookup may in fact only examine the
1451 /// topmost impl. See the comments for `Reveal` for more details.
1453 selcx: &SelectionContext<'_, '_>,
1455 assoc_ty_def_id: DefId,
1456 ) -> specialization_graph::NodeItem<ty::AssocItem> {
1457 let tcx = selcx.tcx();
1458 let assoc_ty_name = tcx.associated_item(assoc_ty_def_id).ident;
1459 let trait_def_id = tcx.impl_trait_ref(impl_def_id).unwrap().def_id;
1460 let trait_def = tcx.trait_def(trait_def_id);
1462 // This function may be called while we are still building the
1463 // specialization graph that is queried below (via TraidDef::ancestors()),
1464 // so, in order to avoid unnecessary infinite recursion, we manually look
1465 // for the associated item at the given impl.
1466 // If there is no such item in that impl, this function will fail with a
1467 // cycle error if the specialization graph is currently being built.
1468 let impl_node = specialization_graph::Node::Impl(impl_def_id);
1469 for item in impl_node.items(tcx) {
1470 if matches!(item.kind, ty::AssocKind::Type | ty::AssocKind::OpaqueTy)
1471 && tcx.hygienic_eq(item.ident, assoc_ty_name, trait_def_id)
1473 return specialization_graph::NodeItem {
1474 node: specialization_graph::Node::Impl(impl_def_id),
1480 if let Some(assoc_item) =
1481 trait_def.ancestors(tcx, impl_def_id).leaf_def(tcx, assoc_ty_name, ty::AssocKind::Type)
1485 // This is saying that neither the trait nor
1486 // the impl contain a definition for this
1487 // associated type. Normally this situation
1488 // could only arise through a compiler bug --
1489 // if the user wrote a bad item name, it
1490 // should have failed in astconv.
1491 bug!("No associated type `{}` for {}", assoc_ty_name, tcx.def_path_str(impl_def_id))
1497 /// The projection cache. Unlike the standard caches, this can include
1498 /// infcx-dependent type variables, therefore we have to roll the
1499 /// cache back each time we roll a snapshot back, to avoid assumptions
1500 /// on yet-unresolved inference variables. Types with placeholder
1501 /// regions also have to be removed when the respective snapshot ends.
1503 /// Because of that, projection cache entries can be "stranded" and left
1504 /// inaccessible when type variables inside the key are resolved. We make no
1505 /// attempt to recover or remove "stranded" entries, but rather let them be
1506 /// (for the lifetime of the infcx).
1508 /// Entries in the projection cache might contain inference variables
1509 /// that will be resolved by obligations on the projection cache entry (e.g.,
1510 /// when a type parameter in the associated type is constrained through
1511 /// an "RFC 447" projection on the impl).
1513 /// When working with a fulfillment context, the derived obligations of each
1514 /// projection cache entry will be registered on the fulfillcx, so any users
1515 /// that can wait for a fulfillcx fixed point need not care about this. However,
1516 /// users that don't wait for a fixed point (e.g., trait evaluation) have to
1517 /// resolve the obligations themselves to make sure the projected result is
1518 /// ok and avoid issues like #43132.
1520 /// If that is done, after evaluation the obligations, it is a good idea to
1521 /// call `ProjectionCache::complete` to make sure the obligations won't be
1522 /// re-evaluated and avoid an exponential worst-case.
1524 // FIXME: we probably also want some sort of cross-infcx cache here to
1525 // reduce the amount of duplication. Let's see what we get with the Chalk reforms.
1527 pub struct ProjectionCache<'tcx> {
1528 map: SnapshotMap<ProjectionCacheKey<'tcx>, ProjectionCacheEntry<'tcx>>,
1531 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
1532 pub struct ProjectionCacheKey<'tcx> {
1533 ty: ty::ProjectionTy<'tcx>,
1536 impl<'cx, 'tcx> ProjectionCacheKey<'tcx> {
1537 pub fn from_poly_projection_predicate(
1538 selcx: &mut SelectionContext<'cx, 'tcx>,
1539 predicate: &ty::PolyProjectionPredicate<'tcx>,
1541 let infcx = selcx.infcx();
1542 // We don't do cross-snapshot caching of obligations with escaping regions,
1543 // so there's no cache key to use
1544 predicate.no_bound_vars().map(|predicate| ProjectionCacheKey {
1545 // We don't attempt to match up with a specific type-variable state
1546 // from a specific call to `opt_normalize_projection_type` - if
1547 // there's no precise match, the original cache entry is "stranded"
1549 ty: infcx.resolve_vars_if_possible(&predicate.projection_ty),
1554 #[derive(Clone, Debug)]
1555 enum ProjectionCacheEntry<'tcx> {
1559 NormalizedTy(NormalizedTy<'tcx>),
1562 // N.B., intentionally not Clone
1563 pub struct ProjectionCacheSnapshot {
1567 impl<'tcx> ProjectionCache<'tcx> {
1568 pub fn clear(&mut self) {
1572 pub fn snapshot(&mut self) -> ProjectionCacheSnapshot {
1573 ProjectionCacheSnapshot { snapshot: self.map.snapshot() }
1576 pub fn rollback_to(&mut self, snapshot: ProjectionCacheSnapshot) {
1577 self.map.rollback_to(snapshot.snapshot);
1580 pub fn rollback_placeholder(&mut self, snapshot: &ProjectionCacheSnapshot) {
1581 self.map.partial_rollback(&snapshot.snapshot, &|k| k.ty.has_re_placeholders());
1584 pub fn commit(&mut self, snapshot: ProjectionCacheSnapshot) {
1585 self.map.commit(snapshot.snapshot);
1588 /// Try to start normalize `key`; returns an error if
1589 /// normalization already occurred (this error corresponds to a
1590 /// cache hit, so it's actually a good thing).
1593 key: ProjectionCacheKey<'tcx>,
1594 ) -> Result<(), ProjectionCacheEntry<'tcx>> {
1595 if let Some(entry) = self.map.get(&key) {
1596 return Err(entry.clone());
1599 self.map.insert(key, ProjectionCacheEntry::InProgress);
1603 /// Indicates that `key` was normalized to `value`.
1604 fn insert_ty(&mut self, key: ProjectionCacheKey<'tcx>, value: NormalizedTy<'tcx>) {
1606 "ProjectionCacheEntry::insert_ty: adding cache entry: key={:?}, value={:?}",
1609 let fresh_key = self.map.insert(key, ProjectionCacheEntry::NormalizedTy(value));
1610 assert!(!fresh_key, "never started projecting `{:?}`", key);
1613 /// Mark the relevant projection cache key as having its derived obligations
1614 /// complete, so they won't have to be re-computed (this is OK to do in a
1615 /// snapshot - if the snapshot is rolled back, the obligations will be
1616 /// marked as incomplete again).
1617 pub fn complete(&mut self, key: ProjectionCacheKey<'tcx>) {
1618 let ty = match self.map.get(&key) {
1619 Some(&ProjectionCacheEntry::NormalizedTy(ref ty)) => {
1620 debug!("ProjectionCacheEntry::complete({:?}) - completing {:?}", key, ty);
1624 // Type inference could "strand behind" old cache entries. Leave
1625 // them alone for now.
1626 debug!("ProjectionCacheEntry::complete({:?}) - ignoring {:?}", key, value);
1633 ProjectionCacheEntry::NormalizedTy(Normalized { value: ty, obligations: vec![] }),
1637 /// A specialized version of `complete` for when the key's value is known
1638 /// to be a NormalizedTy.
1639 pub fn complete_normalized(&mut self, key: ProjectionCacheKey<'tcx>, ty: &NormalizedTy<'tcx>) {
1640 // We want to insert `ty` with no obligations. If the existing value
1641 // already has no obligations (as is common) we don't insert anything.
1642 if !ty.obligations.is_empty() {
1645 ProjectionCacheEntry::NormalizedTy(Normalized {
1647 obligations: vec![],
1653 /// Indicates that trying to normalize `key` resulted in
1654 /// ambiguity. No point in trying it again then until we gain more
1655 /// type information (in which case, the "fully resolved" key will
1657 fn ambiguous(&mut self, key: ProjectionCacheKey<'tcx>) {
1658 let fresh = self.map.insert(key, ProjectionCacheEntry::Ambiguous);
1659 assert!(!fresh, "never started projecting `{:?}`", key);
1662 /// Indicates that trying to normalize `key` resulted in
1664 fn error(&mut self, key: ProjectionCacheKey<'tcx>) {
1665 let fresh = self.map.insert(key, ProjectionCacheEntry::Error);
1666 assert!(!fresh, "never started projecting `{:?}`", key);