1 //! Code for projecting associated types out of trait references.
3 use super::elaborate_predicates;
4 use super::specialization_graph;
5 use super::translate_substs;
7 use super::MismatchedProjectionTypes;
9 use super::ObligationCause;
10 use super::PredicateObligation;
12 use super::SelectionContext;
13 use super::SelectionError;
14 use super::{Normalized, NormalizedTy, ProjectionCacheEntry, ProjectionCacheKey};
15 use super::{VtableClosureData, VtableFnPointerData, VtableGeneratorData, VtableImplData};
17 use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
18 use crate::infer::{InferCtxt, InferOk, LateBoundRegionConversionTime};
19 use crate::traits::error_reporting::InferCtxtExt;
20 use rustc::ty::fold::{TypeFoldable, TypeFolder};
21 use rustc::ty::subst::{InternalSubsts, Subst};
22 use rustc::ty::{self, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, WithConstness};
23 use rustc_ast::ast::Ident;
24 use rustc_errors::ErrorReported;
25 use rustc_hir::def_id::DefId;
26 use rustc_span::symbol::sym;
27 use rustc_span::DUMMY_SP;
29 pub use rustc::traits::Reveal;
31 pub type PolyProjectionObligation<'tcx> = Obligation<'tcx, ty::PolyProjectionPredicate<'tcx>>;
33 pub type ProjectionObligation<'tcx> = Obligation<'tcx, ty::ProjectionPredicate<'tcx>>;
35 pub type ProjectionTyObligation<'tcx> = Obligation<'tcx, ty::ProjectionTy<'tcx>>;
37 /// When attempting to resolve `<T as TraitRef>::Name` ...
39 pub enum ProjectionTyError<'tcx> {
40 /// ...we found multiple sources of information and couldn't resolve the ambiguity.
43 /// ...an error occurred matching `T : TraitRef`
44 TraitSelectionError(SelectionError<'tcx>),
47 #[derive(PartialEq, Eq, Debug)]
48 enum ProjectionTyCandidate<'tcx> {
49 // from a where-clause in the env or object type
50 ParamEnv(ty::PolyProjectionPredicate<'tcx>),
52 // from the definition of `Trait` when you have something like <<A as Trait>::B as Trait2>::C
53 TraitDef(ty::PolyProjectionPredicate<'tcx>),
55 // from a "impl" (or a "pseudo-impl" returned by select)
56 Select(Selection<'tcx>),
59 enum ProjectionTyCandidateSet<'tcx> {
61 Single(ProjectionTyCandidate<'tcx>),
63 Error(SelectionError<'tcx>),
66 impl<'tcx> ProjectionTyCandidateSet<'tcx> {
67 fn mark_ambiguous(&mut self) {
68 *self = ProjectionTyCandidateSet::Ambiguous;
71 fn mark_error(&mut self, err: SelectionError<'tcx>) {
72 *self = ProjectionTyCandidateSet::Error(err);
75 // Returns true if the push was successful, or false if the candidate
76 // was discarded -- this could be because of ambiguity, or because
77 // a higher-priority candidate is already there.
78 fn push_candidate(&mut self, candidate: ProjectionTyCandidate<'tcx>) -> bool {
79 use self::ProjectionTyCandidate::*;
80 use self::ProjectionTyCandidateSet::*;
82 // This wacky variable is just used to try and
83 // make code readable and avoid confusing paths.
84 // It is assigned a "value" of `()` only on those
85 // paths in which we wish to convert `*self` to
86 // ambiguous (and return false, because the candidate
87 // was not used). On other paths, it is not assigned,
88 // and hence if those paths *could* reach the code that
89 // comes after the match, this fn would not compile.
90 let convert_to_ambiguous;
94 *self = Single(candidate);
99 // Duplicates can happen inside ParamEnv. In the case, we
100 // perform a lazy deduplication.
101 if current == &candidate {
105 // Prefer where-clauses. As in select, if there are multiple
106 // candidates, we prefer where-clause candidates over impls. This
107 // may seem a bit surprising, since impls are the source of
108 // "truth" in some sense, but in fact some of the impls that SEEM
109 // applicable are not, because of nested obligations. Where
110 // clauses are the safer choice. See the comment on
111 // `select::SelectionCandidate` and #21974 for more details.
112 match (current, candidate) {
113 (ParamEnv(..), ParamEnv(..)) => convert_to_ambiguous = (),
114 (ParamEnv(..), _) => return false,
115 (_, ParamEnv(..)) => unreachable!(),
116 (_, _) => convert_to_ambiguous = (),
120 Ambiguous | Error(..) => {
125 // We only ever get here when we moved from a single candidate
127 let () = convert_to_ambiguous;
133 /// Evaluates constraints of the form:
135 /// for<...> <T as Trait>::U == V
137 /// If successful, this may result in additional obligations. Also returns
138 /// the projection cache key used to track these additional obligations.
139 pub fn poly_project_and_unify_type<'cx, 'tcx>(
140 selcx: &mut SelectionContext<'cx, 'tcx>,
141 obligation: &PolyProjectionObligation<'tcx>,
142 ) -> Result<Option<Vec<PredicateObligation<'tcx>>>, MismatchedProjectionTypes<'tcx>> {
143 debug!("poly_project_and_unify_type(obligation={:?})", obligation);
145 let infcx = selcx.infcx();
146 infcx.commit_if_ok(|snapshot| {
147 let (placeholder_predicate, placeholder_map) =
148 infcx.replace_bound_vars_with_placeholders(&obligation.predicate);
150 let placeholder_obligation = obligation.with(placeholder_predicate);
151 let result = project_and_unify_type(selcx, &placeholder_obligation)?;
153 .leak_check(false, &placeholder_map, snapshot)
154 .map_err(|err| MismatchedProjectionTypes { err })?;
159 /// Evaluates constraints of the form:
161 /// <T as Trait>::U == V
163 /// If successful, this may result in additional obligations.
164 fn project_and_unify_type<'cx, 'tcx>(
165 selcx: &mut SelectionContext<'cx, 'tcx>,
166 obligation: &ProjectionObligation<'tcx>,
167 ) -> Result<Option<Vec<PredicateObligation<'tcx>>>, MismatchedProjectionTypes<'tcx>> {
168 debug!("project_and_unify_type(obligation={:?})", obligation);
170 let mut obligations = vec![];
171 let normalized_ty = match opt_normalize_projection_type(
173 obligation.param_env,
174 obligation.predicate.projection_ty,
175 obligation.cause.clone(),
176 obligation.recursion_depth,
180 None => return Ok(None),
184 "project_and_unify_type: normalized_ty={:?} obligations={:?}",
185 normalized_ty, obligations
188 let infcx = selcx.infcx();
190 .at(&obligation.cause, obligation.param_env)
191 .eq(normalized_ty, obligation.predicate.ty)
193 Ok(InferOk { obligations: inferred_obligations, value: () }) => {
194 obligations.extend(inferred_obligations);
195 Ok(Some(obligations))
198 debug!("project_and_unify_type: equating types encountered error {:?}", err);
199 Err(MismatchedProjectionTypes { err })
204 /// Normalizes any associated type projections in `value`, replacing
205 /// them with a fully resolved type where possible. The return value
206 /// combines the normalized result and any additional obligations that
207 /// were incurred as result.
208 pub fn normalize<'a, 'b, 'tcx, T>(
209 selcx: &'a mut SelectionContext<'b, 'tcx>,
210 param_env: ty::ParamEnv<'tcx>,
211 cause: ObligationCause<'tcx>,
213 ) -> Normalized<'tcx, T>
215 T: TypeFoldable<'tcx>,
217 let mut obligations = Vec::new();
218 let value = normalize_to(selcx, param_env, cause, value, &mut obligations);
219 Normalized { value, obligations }
222 pub fn normalize_to<'a, 'b, 'tcx, T>(
223 selcx: &'a mut SelectionContext<'b, 'tcx>,
224 param_env: ty::ParamEnv<'tcx>,
225 cause: ObligationCause<'tcx>,
227 obligations: &mut Vec<PredicateObligation<'tcx>>,
230 T: TypeFoldable<'tcx>,
232 normalize_with_depth_to(selcx, param_env, cause, 0, value, obligations)
235 /// As `normalize`, but with a custom depth.
236 pub fn normalize_with_depth<'a, 'b, 'tcx, T>(
237 selcx: &'a mut SelectionContext<'b, 'tcx>,
238 param_env: ty::ParamEnv<'tcx>,
239 cause: ObligationCause<'tcx>,
242 ) -> Normalized<'tcx, T>
244 T: TypeFoldable<'tcx>,
246 let mut obligations = Vec::new();
247 let value = normalize_with_depth_to(selcx, param_env, cause, depth, value, &mut obligations);
248 Normalized { value, obligations }
251 pub fn normalize_with_depth_to<'a, 'b, 'tcx, T>(
252 selcx: &'a mut SelectionContext<'b, 'tcx>,
253 param_env: ty::ParamEnv<'tcx>,
254 cause: ObligationCause<'tcx>,
257 obligations: &mut Vec<PredicateObligation<'tcx>>,
260 T: TypeFoldable<'tcx>,
262 debug!("normalize_with_depth(depth={}, value={:?})", depth, value);
263 let mut normalizer = AssocTypeNormalizer::new(selcx, param_env, cause, depth, obligations);
264 let result = normalizer.fold(value);
266 "normalize_with_depth: depth={} result={:?} with {} obligations",
269 normalizer.obligations.len()
271 debug!("normalize_with_depth: depth={} obligations={:?}", depth, normalizer.obligations);
275 struct AssocTypeNormalizer<'a, 'b, 'tcx> {
276 selcx: &'a mut SelectionContext<'b, 'tcx>,
277 param_env: ty::ParamEnv<'tcx>,
278 cause: ObligationCause<'tcx>,
279 obligations: &'a mut Vec<PredicateObligation<'tcx>>,
283 impl<'a, 'b, 'tcx> AssocTypeNormalizer<'a, 'b, 'tcx> {
285 selcx: &'a mut SelectionContext<'b, 'tcx>,
286 param_env: ty::ParamEnv<'tcx>,
287 cause: ObligationCause<'tcx>,
289 obligations: &'a mut Vec<PredicateObligation<'tcx>>,
290 ) -> AssocTypeNormalizer<'a, 'b, 'tcx> {
291 AssocTypeNormalizer { selcx, param_env, cause, obligations, depth }
294 fn fold<T: TypeFoldable<'tcx>>(&mut self, value: &T) -> T {
295 let value = self.selcx.infcx().resolve_vars_if_possible(value);
297 if !value.has_projections() { value } else { value.fold_with(self) }
301 impl<'a, 'b, 'tcx> TypeFolder<'tcx> for AssocTypeNormalizer<'a, 'b, 'tcx> {
302 fn tcx<'c>(&'c self) -> TyCtxt<'tcx> {
306 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
307 if !ty.has_projections() {
310 // We don't want to normalize associated types that occur inside of region
311 // binders, because they may contain bound regions, and we can't cope with that.
315 // for<'a> fn(<T as Foo<&'a>>::A)
317 // Instead of normalizing `<T as Foo<&'a>>::A` here, we'll
318 // normalize it when we instantiate those bound regions (which
319 // should occur eventually).
321 let ty = ty.super_fold_with(self);
323 ty::Opaque(def_id, substs) if !substs.has_escaping_bound_vars() => {
325 // Only normalize `impl Trait` after type-checking, usually in codegen.
326 match self.param_env.reveal {
327 Reveal::UserFacing => ty,
330 let recursion_limit = *self.tcx().sess.recursion_limit.get();
331 if self.depth >= recursion_limit {
332 let obligation = Obligation::with_depth(
338 self.selcx.infcx().report_overflow_error(&obligation, true);
341 let generic_ty = self.tcx().type_of(def_id);
342 let concrete_ty = generic_ty.subst(self.tcx(), substs);
344 let folded_ty = self.fold_ty(concrete_ty);
351 ty::Projection(ref data) if !data.has_escaping_bound_vars() => {
354 // (*) This is kind of hacky -- we need to be able to
355 // handle normalization within binders because
356 // otherwise we wind up a need to normalize when doing
357 // trait matching (since you can have a trait
358 // obligation like `for<'a> T::B : Fn(&'a int)`), but
359 // we can't normalize with bound regions in scope. So
360 // far now we just ignore binders but only normalize
361 // if all bound regions are gone (and then we still
362 // have to renormalize whenever we instantiate a
363 // binder). It would be better to normalize in a
364 // binding-aware fashion.
366 let normalized_ty = normalize_projection_type(
372 &mut self.obligations,
375 "AssocTypeNormalizer: depth={} normalized {:?} to {:?}, \
376 now with {} obligations",
380 self.obligations.len()
389 fn fold_const(&mut self, constant: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
390 constant.eval(self.selcx.tcx(), self.param_env)
394 /// The guts of `normalize`: normalize a specific projection like `<T
395 /// as Trait>::Item`. The result is always a type (and possibly
396 /// additional obligations). If ambiguity arises, which implies that
397 /// there are unresolved type variables in the projection, we will
398 /// substitute a fresh type variable `$X` and generate a new
399 /// obligation `<T as Trait>::Item == $X` for later.
400 pub fn normalize_projection_type<'a, 'b, 'tcx>(
401 selcx: &'a mut SelectionContext<'b, 'tcx>,
402 param_env: ty::ParamEnv<'tcx>,
403 projection_ty: ty::ProjectionTy<'tcx>,
404 cause: ObligationCause<'tcx>,
406 obligations: &mut Vec<PredicateObligation<'tcx>>,
408 opt_normalize_projection_type(
416 .unwrap_or_else(move || {
417 // if we bottom out in ambiguity, create a type variable
418 // and a deferred predicate to resolve this when more type
419 // information is available.
421 let tcx = selcx.infcx().tcx;
422 let def_id = projection_ty.item_def_id;
423 let ty_var = selcx.infcx().next_ty_var(TypeVariableOrigin {
424 kind: TypeVariableOriginKind::NormalizeProjectionType,
425 span: tcx.def_span(def_id),
427 let projection = ty::Binder::dummy(ty::ProjectionPredicate { projection_ty, ty: ty_var });
429 Obligation::with_depth(cause, depth + 1, param_env, projection.to_predicate());
430 obligations.push(obligation);
435 /// The guts of `normalize`: normalize a specific projection like `<T
436 /// as Trait>::Item`. The result is always a type (and possibly
437 /// additional obligations). Returns `None` in the case of ambiguity,
438 /// which indicates that there are unbound type variables.
440 /// This function used to return `Option<NormalizedTy<'tcx>>`, which contains a
441 /// `Ty<'tcx>` and an obligations vector. But that obligation vector was very
442 /// often immediately appended to another obligations vector. So now this
443 /// function takes an obligations vector and appends to it directly, which is
444 /// slightly uglier but avoids the need for an extra short-lived allocation.
445 fn opt_normalize_projection_type<'a, 'b, 'tcx>(
446 selcx: &'a mut SelectionContext<'b, 'tcx>,
447 param_env: ty::ParamEnv<'tcx>,
448 projection_ty: ty::ProjectionTy<'tcx>,
449 cause: ObligationCause<'tcx>,
451 obligations: &mut Vec<PredicateObligation<'tcx>>,
452 ) -> Option<Ty<'tcx>> {
453 let infcx = selcx.infcx();
455 let projection_ty = infcx.resolve_vars_if_possible(&projection_ty);
456 let cache_key = ProjectionCacheKey::new(projection_ty);
459 "opt_normalize_projection_type(\
460 projection_ty={:?}, \
465 // FIXME(#20304) For now, I am caching here, which is good, but it
466 // means we don't capture the type variables that are created in
467 // the case of ambiguity. Which means we may create a large stream
468 // of such variables. OTOH, if we move the caching up a level, we
469 // would not benefit from caching when proving `T: Trait<U=Foo>`
470 // bounds. It might be the case that we want two distinct caches,
471 // or else another kind of cache entry.
473 let cache_result = infcx.inner.borrow_mut().projection_cache.try_start(cache_key);
476 Err(ProjectionCacheEntry::Ambiguous) => {
477 // If we found ambiguity the last time, that means we will continue
478 // to do so until some type in the key changes (and we know it
479 // hasn't, because we just fully resolved it).
481 "opt_normalize_projection_type: \
482 found cache entry: ambiguous"
486 Err(ProjectionCacheEntry::InProgress) => {
487 // If while normalized A::B, we are asked to normalize
488 // A::B, just return A::B itself. This is a conservative
489 // answer, in the sense that A::B *is* clearly equivalent
490 // to A::B, though there may be a better value we can
493 // Under lazy normalization, this can arise when
494 // bootstrapping. That is, imagine an environment with a
495 // where-clause like `A::B == u32`. Now, if we are asked
496 // to normalize `A::B`, we will want to check the
497 // where-clauses in scope. So we will try to unify `A::B`
498 // with `A::B`, which can trigger a recursive
499 // normalization. In that case, I think we will want this code:
502 // let ty = selcx.tcx().mk_projection(projection_ty.item_def_id,
503 // projection_ty.substs;
504 // return Some(NormalizedTy { value: v, obligations: vec![] });
508 "opt_normalize_projection_type: \
509 found cache entry: in-progress"
512 // But for now, let's classify this as an overflow:
513 let recursion_limit = *selcx.tcx().sess.recursion_limit.get();
515 Obligation::with_depth(cause, recursion_limit, param_env, projection_ty);
516 selcx.infcx().report_overflow_error(&obligation, false);
518 Err(ProjectionCacheEntry::NormalizedTy(ty)) => {
519 // This is the hottest path in this function.
521 // If we find the value in the cache, then return it along
522 // with the obligations that went along with it. Note
523 // that, when using a fulfillment context, these
524 // obligations could in principle be ignored: they have
525 // already been registered when the cache entry was
526 // created (and hence the new ones will quickly be
527 // discarded as duplicated). But when doing trait
528 // evaluation this is not the case, and dropping the trait
529 // evaluations can causes ICEs (e.g., #43132).
531 "opt_normalize_projection_type: \
532 found normalized ty `{:?}`",
536 // Once we have inferred everything we need to know, we
537 // can ignore the `obligations` from that point on.
538 if infcx.unresolved_type_vars(&ty.value).is_none() {
539 infcx.inner.borrow_mut().projection_cache.complete_normalized(cache_key, &ty);
540 // No need to extend `obligations`.
542 obligations.extend(ty.obligations);
545 obligations.push(get_paranoid_cache_value_obligation(
552 return Some(ty.value);
554 Err(ProjectionCacheEntry::Error) => {
556 "opt_normalize_projection_type: \
559 let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth);
560 obligations.extend(result.obligations);
561 return Some(result.value);
565 let obligation = Obligation::with_depth(cause.clone(), depth, param_env, projection_ty);
566 match project_type(selcx, &obligation) {
567 Ok(ProjectedTy::Progress(Progress {
569 obligations: mut projected_obligations,
571 // if projection succeeded, then what we get out of this
572 // is also non-normalized (consider: it was derived from
573 // an impl, where-clause etc) and hence we must
577 "opt_normalize_projection_type: \
580 projected_obligations={:?}",
581 projected_ty, depth, projected_obligations
584 let result = if projected_ty.has_projections() {
585 let mut normalizer = AssocTypeNormalizer::new(
590 &mut projected_obligations,
592 let normalized_ty = normalizer.fold(&projected_ty);
595 "opt_normalize_projection_type: \
596 normalized_ty={:?} depth={}",
600 Normalized { value: normalized_ty, obligations: projected_obligations }
602 Normalized { value: projected_ty, obligations: projected_obligations }
605 let cache_value = prune_cache_value_obligations(infcx, &result);
606 infcx.inner.borrow_mut().projection_cache.insert_ty(cache_key, cache_value);
607 obligations.extend(result.obligations);
610 Ok(ProjectedTy::NoProgress(projected_ty)) => {
612 "opt_normalize_projection_type: \
613 projected_ty={:?} no progress",
616 let result = Normalized { value: projected_ty, obligations: vec![] };
617 infcx.inner.borrow_mut().projection_cache.insert_ty(cache_key, result.clone());
618 // No need to extend `obligations`.
621 Err(ProjectionTyError::TooManyCandidates) => {
623 "opt_normalize_projection_type: \
626 infcx.inner.borrow_mut().projection_cache.ambiguous(cache_key);
629 Err(ProjectionTyError::TraitSelectionError(_)) => {
630 debug!("opt_normalize_projection_type: ERROR");
631 // if we got an error processing the `T as Trait` part,
632 // just return `ty::err` but add the obligation `T :
633 // Trait`, which when processed will cause the error to be
636 infcx.inner.borrow_mut().projection_cache.error(cache_key);
637 let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth);
638 obligations.extend(result.obligations);
644 /// If there are unresolved type variables, then we need to include
645 /// any subobligations that bind them, at least until those type
646 /// variables are fully resolved.
647 fn prune_cache_value_obligations<'a, 'tcx>(
648 infcx: &'a InferCtxt<'a, 'tcx>,
649 result: &NormalizedTy<'tcx>,
650 ) -> NormalizedTy<'tcx> {
651 if infcx.unresolved_type_vars(&result.value).is_none() {
652 return NormalizedTy { value: result.value, obligations: vec![] };
655 let mut obligations: Vec<_> = result
658 .filter(|obligation| match obligation.predicate {
659 // We found a `T: Foo<X = U>` predicate, let's check
660 // if `U` references any unresolved type
661 // variables. In principle, we only care if this
662 // projection can help resolve any of the type
663 // variables found in `result.value` -- but we just
664 // check for any type variables here, for fear of
665 // indirect obligations (e.g., we project to `?0`,
666 // but we have `T: Foo<X = ?1>` and `?1: Bar<X =
668 ty::Predicate::Projection(ref data) => infcx.unresolved_type_vars(&data.ty()).is_some(),
670 // We are only interested in `T: Foo<X = U>` predicates, whre
671 // `U` references one of `unresolved_type_vars`. =)
677 obligations.shrink_to_fit();
679 NormalizedTy { value: result.value, obligations }
682 /// Whenever we give back a cache result for a projection like `<T as
683 /// Trait>::Item ==> X`, we *always* include the obligation to prove
684 /// that `T: Trait` (we may also include some other obligations). This
685 /// may or may not be necessary -- in principle, all the obligations
686 /// that must be proven to show that `T: Trait` were also returned
687 /// when the cache was first populated. But there are some vague concerns,
688 /// and so we take the precautionary measure of including `T: Trait` in
691 /// Concern #1. The current setup is fragile. Perhaps someone could
692 /// have failed to prove the concerns from when the cache was
693 /// populated, but also not have used a snapshot, in which case the
694 /// cache could remain populated even though `T: Trait` has not been
695 /// shown. In this case, the "other code" is at fault -- when you
696 /// project something, you are supposed to either have a snapshot or
697 /// else prove all the resulting obligations -- but it's still easy to
700 /// Concern #2. Even within the snapshot, if those original
701 /// obligations are not yet proven, then we are able to do projections
702 /// that may yet turn out to be wrong. This *may* lead to some sort
703 /// of trouble, though we don't have a concrete example of how that
704 /// can occur yet. But it seems risky at best.
705 fn get_paranoid_cache_value_obligation<'a, 'tcx>(
706 infcx: &'a InferCtxt<'a, 'tcx>,
707 param_env: ty::ParamEnv<'tcx>,
708 projection_ty: ty::ProjectionTy<'tcx>,
709 cause: ObligationCause<'tcx>,
711 ) -> PredicateObligation<'tcx> {
712 let trait_ref = projection_ty.trait_ref(infcx.tcx).to_poly_trait_ref();
715 recursion_depth: depth,
717 predicate: trait_ref.without_const().to_predicate(),
721 /// If we are projecting `<T as Trait>::Item`, but `T: Trait` does not
722 /// hold. In various error cases, we cannot generate a valid
723 /// normalized projection. Therefore, we create an inference variable
724 /// return an associated obligation that, when fulfilled, will lead to
727 /// Note that we used to return `Error` here, but that was quite
728 /// dubious -- the premise was that an error would *eventually* be
729 /// reported, when the obligation was processed. But in general once
730 /// you see a `Error` you are supposed to be able to assume that an
731 /// error *has been* reported, so that you can take whatever heuristic
732 /// paths you want to take. To make things worse, it was possible for
733 /// cycles to arise, where you basically had a setup like `<MyType<$0>
734 /// as Trait>::Foo == $0`. Here, normalizing `<MyType<$0> as
735 /// Trait>::Foo> to `[type error]` would lead to an obligation of
736 /// `<MyType<[type error]> as Trait>::Foo`. We are supposed to report
737 /// an error for this obligation, but we legitimately should not,
738 /// because it contains `[type error]`. Yuck! (See issue #29857 for
739 /// one case where this arose.)
740 fn normalize_to_error<'a, 'tcx>(
741 selcx: &mut SelectionContext<'a, 'tcx>,
742 param_env: ty::ParamEnv<'tcx>,
743 projection_ty: ty::ProjectionTy<'tcx>,
744 cause: ObligationCause<'tcx>,
746 ) -> NormalizedTy<'tcx> {
747 let trait_ref = projection_ty.trait_ref(selcx.tcx()).to_poly_trait_ref();
748 let trait_obligation = Obligation {
750 recursion_depth: depth,
752 predicate: trait_ref.without_const().to_predicate(),
754 let tcx = selcx.infcx().tcx;
755 let def_id = projection_ty.item_def_id;
756 let new_value = selcx.infcx().next_ty_var(TypeVariableOrigin {
757 kind: TypeVariableOriginKind::NormalizeProjectionType,
758 span: tcx.def_span(def_id),
760 Normalized { value: new_value, obligations: vec![trait_obligation] }
763 enum ProjectedTy<'tcx> {
764 Progress(Progress<'tcx>),
765 NoProgress(Ty<'tcx>),
768 struct Progress<'tcx> {
770 obligations: Vec<PredicateObligation<'tcx>>,
773 impl<'tcx> Progress<'tcx> {
774 fn error(tcx: TyCtxt<'tcx>) -> Self {
775 Progress { ty: tcx.types.err, obligations: vec![] }
778 fn with_addl_obligations(mut self, mut obligations: Vec<PredicateObligation<'tcx>>) -> Self {
780 "with_addl_obligations: self.obligations.len={} obligations.len={}",
781 self.obligations.len(),
786 "with_addl_obligations: self.obligations={:?} obligations={:?}",
787 self.obligations, obligations
790 self.obligations.append(&mut obligations);
795 /// Computes the result of a projection type (if we can).
798 /// - `obligation` must be fully normalized
799 fn project_type<'cx, 'tcx>(
800 selcx: &mut SelectionContext<'cx, 'tcx>,
801 obligation: &ProjectionTyObligation<'tcx>,
802 ) -> Result<ProjectedTy<'tcx>, ProjectionTyError<'tcx>> {
803 debug!("project(obligation={:?})", obligation);
805 let recursion_limit = *selcx.tcx().sess.recursion_limit.get();
806 if obligation.recursion_depth >= recursion_limit {
807 debug!("project: overflow!");
808 return Err(ProjectionTyError::TraitSelectionError(SelectionError::Overflow));
811 let obligation_trait_ref = &obligation.predicate.trait_ref(selcx.tcx());
813 debug!("project: obligation_trait_ref={:?}", obligation_trait_ref);
815 if obligation_trait_ref.references_error() {
816 return Ok(ProjectedTy::Progress(Progress::error(selcx.tcx())));
819 let mut candidates = ProjectionTyCandidateSet::None;
821 // Make sure that the following procedures are kept in order. ParamEnv
822 // needs to be first because it has highest priority, and Select checks
823 // the return value of push_candidate which assumes it's ran at last.
824 assemble_candidates_from_param_env(selcx, obligation, &obligation_trait_ref, &mut candidates);
826 assemble_candidates_from_trait_def(selcx, obligation, &obligation_trait_ref, &mut candidates);
828 assemble_candidates_from_impls(selcx, obligation, &obligation_trait_ref, &mut candidates);
831 ProjectionTyCandidateSet::Single(candidate) => Ok(ProjectedTy::Progress(
832 confirm_candidate(selcx, obligation, &obligation_trait_ref, candidate),
834 ProjectionTyCandidateSet::None => Ok(ProjectedTy::NoProgress(
837 .mk_projection(obligation.predicate.item_def_id, obligation.predicate.substs),
839 // Error occurred while trying to processing impls.
840 ProjectionTyCandidateSet::Error(e) => Err(ProjectionTyError::TraitSelectionError(e)),
841 // Inherent ambiguity that prevents us from even enumerating the
843 ProjectionTyCandidateSet::Ambiguous => Err(ProjectionTyError::TooManyCandidates),
847 /// The first thing we have to do is scan through the parameter
848 /// environment to see whether there are any projection predicates
849 /// there that can answer this question.
850 fn assemble_candidates_from_param_env<'cx, 'tcx>(
851 selcx: &mut SelectionContext<'cx, 'tcx>,
852 obligation: &ProjectionTyObligation<'tcx>,
853 obligation_trait_ref: &ty::TraitRef<'tcx>,
854 candidate_set: &mut ProjectionTyCandidateSet<'tcx>,
856 debug!("assemble_candidates_from_param_env(..)");
857 assemble_candidates_from_predicates(
860 obligation_trait_ref,
862 ProjectionTyCandidate::ParamEnv,
863 obligation.param_env.caller_bounds.iter().cloned(),
867 /// In the case of a nested projection like <<A as Foo>::FooT as Bar>::BarT, we may find
868 /// that the definition of `Foo` has some clues:
872 /// type FooT : Bar<BarT=i32>
876 /// Here, for example, we could conclude that the result is `i32`.
877 fn assemble_candidates_from_trait_def<'cx, 'tcx>(
878 selcx: &mut SelectionContext<'cx, 'tcx>,
879 obligation: &ProjectionTyObligation<'tcx>,
880 obligation_trait_ref: &ty::TraitRef<'tcx>,
881 candidate_set: &mut ProjectionTyCandidateSet<'tcx>,
883 debug!("assemble_candidates_from_trait_def(..)");
885 let tcx = selcx.tcx();
886 // Check whether the self-type is itself a projection.
887 let (def_id, substs) = match obligation_trait_ref.self_ty().kind {
888 ty::Projection(ref data) => (data.trait_ref(tcx).def_id, data.substs),
889 ty::Opaque(def_id, substs) => (def_id, substs),
890 ty::Infer(ty::TyVar(_)) => {
891 // If the self-type is an inference variable, then it MAY wind up
892 // being a projected type, so induce an ambiguity.
893 candidate_set.mark_ambiguous();
899 // If so, extract what we know from the trait and try to come up with a good answer.
900 let trait_predicates = tcx.predicates_of(def_id);
901 let bounds = trait_predicates.instantiate(tcx, substs);
902 let bounds = elaborate_predicates(tcx, bounds.predicates);
903 assemble_candidates_from_predicates(
906 obligation_trait_ref,
908 ProjectionTyCandidate::TraitDef,
913 fn assemble_candidates_from_predicates<'cx, 'tcx, I>(
914 selcx: &mut SelectionContext<'cx, 'tcx>,
915 obligation: &ProjectionTyObligation<'tcx>,
916 obligation_trait_ref: &ty::TraitRef<'tcx>,
917 candidate_set: &mut ProjectionTyCandidateSet<'tcx>,
918 ctor: fn(ty::PolyProjectionPredicate<'tcx>) -> ProjectionTyCandidate<'tcx>,
921 I: IntoIterator<Item = ty::Predicate<'tcx>>,
923 debug!("assemble_candidates_from_predicates(obligation={:?})", obligation);
924 let infcx = selcx.infcx();
925 for predicate in env_predicates {
926 debug!("assemble_candidates_from_predicates: predicate={:?}", predicate);
927 if let ty::Predicate::Projection(data) = predicate {
928 let same_def_id = data.projection_def_id() == obligation.predicate.item_def_id;
930 let is_match = same_def_id
932 let data_poly_trait_ref = data.to_poly_trait_ref(infcx.tcx);
933 let obligation_poly_trait_ref = obligation_trait_ref.to_poly_trait_ref();
935 .at(&obligation.cause, obligation.param_env)
936 .sup(obligation_poly_trait_ref, data_poly_trait_ref)
937 .map(|InferOk { obligations: _, value: () }| {
938 // FIXME(#32730) -- do we need to take obligations
939 // into account in any way? At the moment, no.
945 "assemble_candidates_from_predicates: candidate={:?} \
946 is_match={} same_def_id={}",
947 data, is_match, same_def_id
951 candidate_set.push_candidate(ctor(data));
957 fn assemble_candidates_from_impls<'cx, 'tcx>(
958 selcx: &mut SelectionContext<'cx, 'tcx>,
959 obligation: &ProjectionTyObligation<'tcx>,
960 obligation_trait_ref: &ty::TraitRef<'tcx>,
961 candidate_set: &mut ProjectionTyCandidateSet<'tcx>,
963 // If we are resolving `<T as TraitRef<...>>::Item == Type`,
964 // start out by selecting the predicate `T as TraitRef<...>`:
965 let poly_trait_ref = obligation_trait_ref.to_poly_trait_ref();
966 let trait_obligation = obligation.with(poly_trait_ref.to_poly_trait_predicate());
967 let _ = selcx.infcx().commit_if_ok(|_| {
968 let vtable = match selcx.select(&trait_obligation) {
969 Ok(Some(vtable)) => vtable,
971 candidate_set.mark_ambiguous();
975 debug!("assemble_candidates_from_impls: selection error {:?}", e);
976 candidate_set.mark_error(e);
981 let eligible = match &vtable {
982 super::VtableClosure(_)
983 | super::VtableGenerator(_)
984 | super::VtableFnPointer(_)
985 | super::VtableObject(_)
986 | super::VtableTraitAlias(_) => {
987 debug!("assemble_candidates_from_impls: vtable={:?}", vtable);
990 super::VtableImpl(impl_data) => {
991 // We have to be careful when projecting out of an
992 // impl because of specialization. If we are not in
993 // codegen (i.e., projection mode is not "any"), and the
994 // impl's type is declared as default, then we disable
995 // projection (even if the trait ref is fully
996 // monomorphic). In the case where trait ref is not
997 // fully monomorphic (i.e., includes type parameters),
998 // this is because those type parameters may
999 // ultimately be bound to types from other crates that
1000 // may have specialized impls we can't see. In the
1001 // case where the trait ref IS fully monomorphic, this
1002 // is a policy decision that we made in the RFC in
1003 // order to preserve flexibility for the crate that
1004 // defined the specializable impl to specialize later
1005 // for existing types.
1007 // In either case, we handle this by not adding a
1008 // candidate for an impl if it contains a `default`
1011 // NOTE: This should be kept in sync with the similar code in
1012 // `rustc::ty::instance::resolve_associated_item()`.
1014 assoc_ty_def(selcx, impl_data.impl_def_id, obligation.predicate.item_def_id)
1015 .map_err(|ErrorReported| ())?;
1017 let is_default = if node_item.node.is_from_trait() {
1018 // If true, the impl inherited a `type Foo = Bar`
1019 // given in the trait, which is implicitly default.
1020 // Otherwise, the impl did not specify `type` and
1021 // neither did the trait:
1024 // trait Foo { type T; }
1025 // impl Foo for Bar { }
1028 // This is an error, but it will be
1029 // reported in `check_impl_items_against_trait`.
1030 // We accept it here but will flag it as
1031 // an error when we confirm the candidate
1032 // (which will ultimately lead to `normalize_to_error`
1036 // If we're looking at a trait *impl*, the item is
1037 // specializable if the impl or the item are marked
1039 node_item.item.defaultness.is_default()
1040 || super::util::impl_is_default(selcx.tcx(), node_item.node.def_id())
1044 // Non-specializable items are always projectable
1047 // Only reveal a specializable default if we're past type-checking
1048 // and the obligation is monomorphic, otherwise passes such as
1049 // transmute checking and polymorphic MIR optimizations could
1050 // get a result which isn't correct for all monomorphizations.
1051 true if obligation.param_env.reveal == Reveal::All => {
1052 // NOTE(eddyb) inference variables can resolve to parameters, so
1053 // assume `poly_trait_ref` isn't monomorphic, if it contains any.
1054 let poly_trait_ref =
1055 selcx.infcx().resolve_vars_if_possible(&poly_trait_ref);
1056 !poly_trait_ref.needs_infer() && !poly_trait_ref.needs_subst()
1061 "assemble_candidates_from_impls: not eligible due to default: \
1062 assoc_ty={} predicate={}",
1063 selcx.tcx().def_path_str(node_item.item.def_id),
1064 obligation.predicate,
1070 super::VtableParam(..) => {
1071 // This case tell us nothing about the value of an
1072 // associated type. Consider:
1075 // trait SomeTrait { type Foo; }
1076 // fn foo<T:SomeTrait>(...) { }
1079 // If the user writes `<T as SomeTrait>::Foo`, then the `T
1080 // : SomeTrait` binding does not help us decide what the
1081 // type `Foo` is (at least, not more specifically than
1082 // what we already knew).
1084 // But wait, you say! What about an example like this:
1087 // fn bar<T:SomeTrait<Foo=usize>>(...) { ... }
1090 // Doesn't the `T : Sometrait<Foo=usize>` predicate help
1091 // resolve `T::Foo`? And of course it does, but in fact
1092 // that single predicate is desugared into two predicates
1093 // in the compiler: a trait predicate (`T : SomeTrait`) and a
1094 // projection. And the projection where clause is handled
1095 // in `assemble_candidates_from_param_env`.
1098 super::VtableAutoImpl(..) | super::VtableBuiltin(..) => {
1099 // These traits have no associated types.
1101 obligation.cause.span,
1102 "Cannot project an associated type from `{:?}`",
1109 if candidate_set.push_candidate(ProjectionTyCandidate::Select(vtable)) {
1120 fn confirm_candidate<'cx, 'tcx>(
1121 selcx: &mut SelectionContext<'cx, 'tcx>,
1122 obligation: &ProjectionTyObligation<'tcx>,
1123 obligation_trait_ref: &ty::TraitRef<'tcx>,
1124 candidate: ProjectionTyCandidate<'tcx>,
1125 ) -> Progress<'tcx> {
1126 debug!("confirm_candidate(candidate={:?}, obligation={:?})", candidate, obligation);
1129 ProjectionTyCandidate::ParamEnv(poly_projection)
1130 | ProjectionTyCandidate::TraitDef(poly_projection) => {
1131 confirm_param_env_candidate(selcx, obligation, poly_projection)
1134 ProjectionTyCandidate::Select(vtable) => {
1135 confirm_select_candidate(selcx, obligation, obligation_trait_ref, vtable)
1140 fn confirm_select_candidate<'cx, 'tcx>(
1141 selcx: &mut SelectionContext<'cx, 'tcx>,
1142 obligation: &ProjectionTyObligation<'tcx>,
1143 obligation_trait_ref: &ty::TraitRef<'tcx>,
1144 vtable: Selection<'tcx>,
1145 ) -> Progress<'tcx> {
1147 super::VtableImpl(data) => confirm_impl_candidate(selcx, obligation, data),
1148 super::VtableGenerator(data) => confirm_generator_candidate(selcx, obligation, data),
1149 super::VtableClosure(data) => confirm_closure_candidate(selcx, obligation, data),
1150 super::VtableFnPointer(data) => confirm_fn_pointer_candidate(selcx, obligation, data),
1151 super::VtableObject(_) => confirm_object_candidate(selcx, obligation, obligation_trait_ref),
1152 super::VtableAutoImpl(..)
1153 | super::VtableParam(..)
1154 | super::VtableBuiltin(..)
1155 | super::VtableTraitAlias(..) =>
1156 // we don't create Select candidates with this kind of resolution
1159 obligation.cause.span,
1160 "Cannot project an associated type from `{:?}`",
1167 fn confirm_object_candidate<'cx, 'tcx>(
1168 selcx: &mut SelectionContext<'cx, 'tcx>,
1169 obligation: &ProjectionTyObligation<'tcx>,
1170 obligation_trait_ref: &ty::TraitRef<'tcx>,
1171 ) -> Progress<'tcx> {
1172 let self_ty = obligation_trait_ref.self_ty();
1173 let object_ty = selcx.infcx().shallow_resolve(self_ty);
1174 debug!("confirm_object_candidate(object_ty={:?})", object_ty);
1175 let data = match object_ty.kind {
1176 ty::Dynamic(ref data, ..) => data,
1178 obligation.cause.span,
1179 "confirm_object_candidate called with non-object: {:?}",
1183 let env_predicates = data
1184 .projection_bounds()
1185 .map(|p| p.with_self_ty(selcx.tcx(), object_ty).to_predicate())
1187 let env_predicate = {
1188 let env_predicates = elaborate_predicates(selcx.tcx(), env_predicates);
1190 // select only those projections that are actually projecting an
1191 // item with the correct name
1192 let env_predicates = env_predicates.filter_map(|p| match p {
1193 ty::Predicate::Projection(data) => {
1194 if data.projection_def_id() == obligation.predicate.item_def_id {
1203 // select those with a relevant trait-ref
1204 let mut env_predicates = env_predicates.filter(|data| {
1205 let data_poly_trait_ref = data.to_poly_trait_ref(selcx.tcx());
1206 let obligation_poly_trait_ref = obligation_trait_ref.to_poly_trait_ref();
1207 selcx.infcx().probe(|_| {
1210 .at(&obligation.cause, obligation.param_env)
1211 .sup(obligation_poly_trait_ref, data_poly_trait_ref)
1216 // select the first matching one; there really ought to be one or
1217 // else the object type is not WF, since an object type should
1218 // include all of its projections explicitly
1219 match env_predicates.next() {
1220 Some(env_predicate) => env_predicate,
1223 "confirm_object_candidate: no env-predicate \
1224 found in object type `{:?}`; ill-formed",
1227 return Progress::error(selcx.tcx());
1232 confirm_param_env_candidate(selcx, obligation, env_predicate)
1235 fn confirm_generator_candidate<'cx, 'tcx>(
1236 selcx: &mut SelectionContext<'cx, 'tcx>,
1237 obligation: &ProjectionTyObligation<'tcx>,
1238 vtable: VtableGeneratorData<'tcx, PredicateObligation<'tcx>>,
1239 ) -> Progress<'tcx> {
1240 let gen_sig = vtable.substs.as_generator().poly_sig(vtable.generator_def_id, selcx.tcx());
1241 let Normalized { value: gen_sig, obligations } = normalize_with_depth(
1243 obligation.param_env,
1244 obligation.cause.clone(),
1245 obligation.recursion_depth + 1,
1250 "confirm_generator_candidate: obligation={:?},gen_sig={:?},obligations={:?}",
1251 obligation, gen_sig, obligations
1254 let tcx = selcx.tcx();
1256 let gen_def_id = tcx.lang_items().gen_trait().unwrap();
1258 let predicate = super::util::generator_trait_ref_and_outputs(
1261 obligation.predicate.self_ty(),
1264 .map_bound(|(trait_ref, yield_ty, return_ty)| {
1265 let name = tcx.associated_item(obligation.predicate.item_def_id).ident.name;
1266 let ty = if name == sym::Return {
1268 } else if name == sym::Yield {
1274 ty::ProjectionPredicate {
1275 projection_ty: ty::ProjectionTy {
1276 substs: trait_ref.substs,
1277 item_def_id: obligation.predicate.item_def_id,
1283 confirm_param_env_candidate(selcx, obligation, predicate)
1284 .with_addl_obligations(vtable.nested)
1285 .with_addl_obligations(obligations)
1288 fn confirm_fn_pointer_candidate<'cx, 'tcx>(
1289 selcx: &mut SelectionContext<'cx, 'tcx>,
1290 obligation: &ProjectionTyObligation<'tcx>,
1291 fn_pointer_vtable: VtableFnPointerData<'tcx, PredicateObligation<'tcx>>,
1292 ) -> Progress<'tcx> {
1293 let fn_type = selcx.infcx().shallow_resolve(fn_pointer_vtable.fn_ty);
1294 let sig = fn_type.fn_sig(selcx.tcx());
1295 let Normalized { value: sig, obligations } = normalize_with_depth(
1297 obligation.param_env,
1298 obligation.cause.clone(),
1299 obligation.recursion_depth + 1,
1303 confirm_callable_candidate(selcx, obligation, sig, util::TupleArgumentsFlag::Yes)
1304 .with_addl_obligations(fn_pointer_vtable.nested)
1305 .with_addl_obligations(obligations)
1308 fn confirm_closure_candidate<'cx, 'tcx>(
1309 selcx: &mut SelectionContext<'cx, 'tcx>,
1310 obligation: &ProjectionTyObligation<'tcx>,
1311 vtable: VtableClosureData<'tcx, PredicateObligation<'tcx>>,
1312 ) -> Progress<'tcx> {
1313 let tcx = selcx.tcx();
1314 let infcx = selcx.infcx();
1315 let closure_sig_ty = vtable.substs.as_closure().sig_ty(vtable.closure_def_id, tcx);
1316 let closure_sig = infcx.shallow_resolve(closure_sig_ty).fn_sig(tcx);
1317 let Normalized { value: closure_sig, obligations } = normalize_with_depth(
1319 obligation.param_env,
1320 obligation.cause.clone(),
1321 obligation.recursion_depth + 1,
1326 "confirm_closure_candidate: obligation={:?},closure_sig={:?},obligations={:?}",
1327 obligation, closure_sig, obligations
1330 confirm_callable_candidate(selcx, obligation, closure_sig, util::TupleArgumentsFlag::No)
1331 .with_addl_obligations(vtable.nested)
1332 .with_addl_obligations(obligations)
1335 fn confirm_callable_candidate<'cx, 'tcx>(
1336 selcx: &mut SelectionContext<'cx, 'tcx>,
1337 obligation: &ProjectionTyObligation<'tcx>,
1338 fn_sig: ty::PolyFnSig<'tcx>,
1339 flag: util::TupleArgumentsFlag,
1340 ) -> Progress<'tcx> {
1341 let tcx = selcx.tcx();
1343 debug!("confirm_callable_candidate({:?},{:?})", obligation, fn_sig);
1345 // the `Output` associated type is declared on `FnOnce`
1346 let fn_once_def_id = tcx.lang_items().fn_once_trait().unwrap();
1348 let predicate = super::util::closure_trait_ref_and_return_type(
1351 obligation.predicate.self_ty(),
1355 .map_bound(|(trait_ref, ret_type)| ty::ProjectionPredicate {
1356 projection_ty: ty::ProjectionTy::from_ref_and_name(
1359 Ident::with_dummy_span(rustc_hir::FN_OUTPUT_NAME),
1364 confirm_param_env_candidate(selcx, obligation, predicate)
1367 fn confirm_param_env_candidate<'cx, 'tcx>(
1368 selcx: &mut SelectionContext<'cx, 'tcx>,
1369 obligation: &ProjectionTyObligation<'tcx>,
1370 poly_cache_entry: ty::PolyProjectionPredicate<'tcx>,
1371 ) -> Progress<'tcx> {
1372 let infcx = selcx.infcx();
1373 let cause = &obligation.cause;
1374 let param_env = obligation.param_env;
1376 let (cache_entry, _) = infcx.replace_bound_vars_with_fresh_vars(
1378 LateBoundRegionConversionTime::HigherRankedType,
1382 let cache_trait_ref = cache_entry.projection_ty.trait_ref(infcx.tcx);
1383 let obligation_trait_ref = obligation.predicate.trait_ref(infcx.tcx);
1384 match infcx.at(cause, param_env).eq(cache_trait_ref, obligation_trait_ref) {
1385 Ok(InferOk { value: _, obligations }) => Progress { ty: cache_entry.ty, obligations },
1388 "Failed to unify obligation `{:?}` with poly_projection `{:?}`: {:?}",
1389 obligation, poly_cache_entry, e,
1391 debug!("confirm_param_env_candidate: {}", msg);
1392 infcx.tcx.sess.delay_span_bug(obligation.cause.span, &msg);
1393 Progress { ty: infcx.tcx.types.err, obligations: vec![] }
1398 fn confirm_impl_candidate<'cx, 'tcx>(
1399 selcx: &mut SelectionContext<'cx, 'tcx>,
1400 obligation: &ProjectionTyObligation<'tcx>,
1401 impl_vtable: VtableImplData<'tcx, PredicateObligation<'tcx>>,
1402 ) -> Progress<'tcx> {
1403 let tcx = selcx.tcx();
1405 let VtableImplData { impl_def_id, substs, nested } = impl_vtable;
1406 let assoc_item_id = obligation.predicate.item_def_id;
1407 let trait_def_id = tcx.trait_id_of_impl(impl_def_id).unwrap();
1409 let param_env = obligation.param_env;
1410 let assoc_ty = match assoc_ty_def(selcx, impl_def_id, assoc_item_id) {
1411 Ok(assoc_ty) => assoc_ty,
1412 Err(ErrorReported) => return Progress { ty: tcx.types.err, obligations: nested },
1415 if !assoc_ty.item.defaultness.has_value() {
1416 // This means that the impl is missing a definition for the
1417 // associated type. This error will be reported by the type
1418 // checker method `check_impl_items_against_trait`, so here we
1419 // just return Error.
1421 "confirm_impl_candidate: no associated type {:?} for {:?}",
1422 assoc_ty.item.ident, obligation.predicate
1424 return Progress { ty: tcx.types.err, obligations: nested };
1426 let substs = obligation.predicate.substs.rebase_onto(tcx, trait_def_id, substs);
1427 let substs = translate_substs(selcx.infcx(), param_env, impl_def_id, substs, assoc_ty.node);
1428 let ty = if let ty::AssocKind::OpaqueTy = assoc_ty.item.kind {
1429 let item_substs = InternalSubsts::identity_for_item(tcx, assoc_ty.item.def_id);
1430 tcx.mk_opaque(assoc_ty.item.def_id, item_substs)
1432 tcx.type_of(assoc_ty.item.def_id)
1434 if substs.len() != tcx.generics_of(assoc_ty.item.def_id).count() {
1436 .delay_span_bug(DUMMY_SP, "impl item and trait item have different parameter counts");
1437 Progress { ty: tcx.types.err, obligations: nested }
1439 Progress { ty: ty.subst(tcx, substs), obligations: nested }
1443 /// Locate the definition of an associated type in the specialization hierarchy,
1444 /// starting from the given impl.
1446 /// Based on the "projection mode", this lookup may in fact only examine the
1447 /// topmost impl. See the comments for `Reveal` for more details.
1449 selcx: &SelectionContext<'_, '_>,
1451 assoc_ty_def_id: DefId,
1452 ) -> Result<specialization_graph::NodeItem<ty::AssocItem>, ErrorReported> {
1453 let tcx = selcx.tcx();
1454 let assoc_ty_name = tcx.associated_item(assoc_ty_def_id).ident;
1455 let trait_def_id = tcx.impl_trait_ref(impl_def_id).unwrap().def_id;
1456 let trait_def = tcx.trait_def(trait_def_id);
1458 // This function may be called while we are still building the
1459 // specialization graph that is queried below (via TraitDef::ancestors()),
1460 // so, in order to avoid unnecessary infinite recursion, we manually look
1461 // for the associated item at the given impl.
1462 // If there is no such item in that impl, this function will fail with a
1463 // cycle error if the specialization graph is currently being built.
1464 let impl_node = specialization_graph::Node::Impl(impl_def_id);
1465 for item in impl_node.items(tcx) {
1466 if matches!(item.kind, ty::AssocKind::Type | ty::AssocKind::OpaqueTy)
1467 && tcx.hygienic_eq(item.ident, assoc_ty_name, trait_def_id)
1469 return Ok(specialization_graph::NodeItem {
1470 node: specialization_graph::Node::Impl(impl_def_id),
1476 let ancestors = trait_def.ancestors(tcx, impl_def_id)?;
1477 if let Some(assoc_item) = ancestors.leaf_def(tcx, assoc_ty_name, ty::AssocKind::Type) {
1480 // This is saying that neither the trait nor
1481 // the impl contain a definition for this
1482 // associated type. Normally this situation
1483 // could only arise through a compiler bug --
1484 // if the user wrote a bad item name, it
1485 // should have failed in astconv.
1486 bug!("No associated type `{}` for {}", assoc_ty_name, tcx.def_path_str(impl_def_id))
1490 crate trait ProjectionCacheKeyExt<'tcx>: Sized {
1491 fn from_poly_projection_predicate(
1492 selcx: &mut SelectionContext<'cx, 'tcx>,
1493 predicate: &ty::PolyProjectionPredicate<'tcx>,
1497 impl<'tcx> ProjectionCacheKeyExt<'tcx> for ProjectionCacheKey<'tcx> {
1498 fn from_poly_projection_predicate(
1499 selcx: &mut SelectionContext<'cx, 'tcx>,
1500 predicate: &ty::PolyProjectionPredicate<'tcx>,
1502 let infcx = selcx.infcx();
1503 // We don't do cross-snapshot caching of obligations with escaping regions,
1504 // so there's no cache key to use
1505 predicate.no_bound_vars().map(|predicate| {
1506 ProjectionCacheKey::new(
1507 // We don't attempt to match up with a specific type-variable state
1508 // from a specific call to `opt_normalize_projection_type` - if
1509 // there's no precise match, the original cache entry is "stranded"
1511 infcx.resolve_vars_if_possible(&predicate.projection_ty),