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;
15 ImplSourceClosureData, ImplSourceDiscriminantKindData, ImplSourceFnPointerData,
16 ImplSourceGeneratorData, ImplSourceUserDefinedData,
18 use super::{Normalized, NormalizedTy, ProjectionCacheEntry, ProjectionCacheKey};
20 use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
21 use crate::infer::{InferCtxt, InferOk, LateBoundRegionConversionTime};
22 use crate::traits::error_reporting::InferCtxtExt;
23 use rustc_data_structures::stack::ensure_sufficient_stack;
24 use rustc_errors::ErrorReported;
25 use rustc_hir::def_id::DefId;
26 use rustc_hir::lang_items::{
27 DiscriminantTypeLangItem, FnOnceOutputLangItem, FnOnceTraitLangItem, GeneratorTraitLangItem,
29 use rustc_infer::infer::resolve::OpportunisticRegionResolver;
30 use rustc_middle::ty::fold::{TypeFoldable, TypeFolder};
31 use rustc_middle::ty::subst::Subst;
32 use rustc_middle::ty::{self, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, WithConstness};
33 use rustc_span::symbol::sym;
34 use rustc_span::DUMMY_SP;
36 pub use rustc_middle::traits::Reveal;
38 pub type PolyProjectionObligation<'tcx> = Obligation<'tcx, ty::PolyProjectionPredicate<'tcx>>;
40 pub type ProjectionObligation<'tcx> = Obligation<'tcx, ty::ProjectionPredicate<'tcx>>;
42 pub type ProjectionTyObligation<'tcx> = Obligation<'tcx, ty::ProjectionTy<'tcx>>;
44 /// When attempting to resolve `<T as TraitRef>::Name` ...
46 pub enum ProjectionTyError<'tcx> {
47 /// ...we found multiple sources of information and couldn't resolve the ambiguity.
50 /// ...an error occurred matching `T : TraitRef`
51 TraitSelectionError(SelectionError<'tcx>),
54 #[derive(PartialEq, Eq, Debug)]
55 enum ProjectionTyCandidate<'tcx> {
56 // from a where-clause in the env or object type
57 ParamEnv(ty::PolyProjectionPredicate<'tcx>),
59 // from the definition of `Trait` when you have something like <<A as Trait>::B as Trait2>::C
60 TraitDef(ty::PolyProjectionPredicate<'tcx>),
62 // from a "impl" (or a "pseudo-impl" returned by select)
63 Select(Selection<'tcx>),
66 enum ProjectionTyCandidateSet<'tcx> {
68 Single(ProjectionTyCandidate<'tcx>),
70 Error(SelectionError<'tcx>),
73 impl<'tcx> ProjectionTyCandidateSet<'tcx> {
74 fn mark_ambiguous(&mut self) {
75 *self = ProjectionTyCandidateSet::Ambiguous;
78 fn mark_error(&mut self, err: SelectionError<'tcx>) {
79 *self = ProjectionTyCandidateSet::Error(err);
82 // Returns true if the push was successful, or false if the candidate
83 // was discarded -- this could be because of ambiguity, or because
84 // a higher-priority candidate is already there.
85 fn push_candidate(&mut self, candidate: ProjectionTyCandidate<'tcx>) -> bool {
86 use self::ProjectionTyCandidate::*;
87 use self::ProjectionTyCandidateSet::*;
89 // This wacky variable is just used to try and
90 // make code readable and avoid confusing paths.
91 // It is assigned a "value" of `()` only on those
92 // paths in which we wish to convert `*self` to
93 // ambiguous (and return false, because the candidate
94 // was not used). On other paths, it is not assigned,
95 // and hence if those paths *could* reach the code that
96 // comes after the match, this fn would not compile.
97 let convert_to_ambiguous;
101 *self = Single(candidate);
106 // Duplicates can happen inside ParamEnv. In the case, we
107 // perform a lazy deduplication.
108 if current == &candidate {
112 // Prefer where-clauses. As in select, if there are multiple
113 // candidates, we prefer where-clause candidates over impls. This
114 // may seem a bit surprising, since impls are the source of
115 // "truth" in some sense, but in fact some of the impls that SEEM
116 // applicable are not, because of nested obligations. Where
117 // clauses are the safer choice. See the comment on
118 // `select::SelectionCandidate` and #21974 for more details.
119 match (current, candidate) {
120 (ParamEnv(..), ParamEnv(..)) => convert_to_ambiguous = (),
121 (ParamEnv(..), _) => return false,
122 (_, ParamEnv(..)) => unreachable!(),
123 (_, _) => convert_to_ambiguous = (),
127 Ambiguous | Error(..) => {
132 // We only ever get here when we moved from a single candidate
134 let () = convert_to_ambiguous;
140 /// Evaluates constraints of the form:
142 /// for<...> <T as Trait>::U == V
144 /// If successful, this may result in additional obligations. Also returns
145 /// the projection cache key used to track these additional obligations.
146 pub fn poly_project_and_unify_type<'cx, 'tcx>(
147 selcx: &mut SelectionContext<'cx, 'tcx>,
148 obligation: &PolyProjectionObligation<'tcx>,
149 ) -> Result<Option<Vec<PredicateObligation<'tcx>>>, MismatchedProjectionTypes<'tcx>> {
150 debug!("poly_project_and_unify_type(obligation={:?})", obligation);
152 let infcx = selcx.infcx();
153 infcx.commit_if_ok(|_snapshot| {
154 let (placeholder_predicate, _) =
155 infcx.replace_bound_vars_with_placeholders(&obligation.predicate);
157 let placeholder_obligation = obligation.with(placeholder_predicate);
158 let result = project_and_unify_type(selcx, &placeholder_obligation)?;
163 /// Evaluates constraints of the form:
165 /// <T as Trait>::U == V
167 /// If successful, this may result in additional obligations.
168 fn project_and_unify_type<'cx, 'tcx>(
169 selcx: &mut SelectionContext<'cx, 'tcx>,
170 obligation: &ProjectionObligation<'tcx>,
171 ) -> Result<Option<Vec<PredicateObligation<'tcx>>>, MismatchedProjectionTypes<'tcx>> {
172 debug!("project_and_unify_type(obligation={:?})", obligation);
174 let mut obligations = vec![];
175 let normalized_ty = match opt_normalize_projection_type(
177 obligation.param_env,
178 obligation.predicate.projection_ty,
179 obligation.cause.clone(),
180 obligation.recursion_depth,
184 None => return Ok(None),
188 "project_and_unify_type: normalized_ty={:?} obligations={:?}",
189 normalized_ty, obligations
192 let infcx = selcx.infcx();
194 .at(&obligation.cause, obligation.param_env)
195 .eq(normalized_ty, obligation.predicate.ty)
197 Ok(InferOk { obligations: inferred_obligations, value: () }) => {
198 obligations.extend(inferred_obligations);
199 Ok(Some(obligations))
202 debug!("project_and_unify_type: equating types encountered error {:?}", err);
203 Err(MismatchedProjectionTypes { err })
208 /// Normalizes any associated type projections in `value`, replacing
209 /// them with a fully resolved type where possible. The return value
210 /// combines the normalized result and any additional obligations that
211 /// were incurred as result.
212 pub fn normalize<'a, 'b, 'tcx, T>(
213 selcx: &'a mut SelectionContext<'b, 'tcx>,
214 param_env: ty::ParamEnv<'tcx>,
215 cause: ObligationCause<'tcx>,
217 ) -> Normalized<'tcx, T>
219 T: TypeFoldable<'tcx>,
221 let mut obligations = Vec::new();
222 let value = normalize_to(selcx, param_env, cause, value, &mut obligations);
223 Normalized { value, obligations }
226 pub fn normalize_to<'a, 'b, 'tcx, T>(
227 selcx: &'a mut SelectionContext<'b, 'tcx>,
228 param_env: ty::ParamEnv<'tcx>,
229 cause: ObligationCause<'tcx>,
231 obligations: &mut Vec<PredicateObligation<'tcx>>,
234 T: TypeFoldable<'tcx>,
236 normalize_with_depth_to(selcx, param_env, cause, 0, value, obligations)
239 /// As `normalize`, but with a custom depth.
240 pub fn normalize_with_depth<'a, 'b, 'tcx, T>(
241 selcx: &'a mut SelectionContext<'b, 'tcx>,
242 param_env: ty::ParamEnv<'tcx>,
243 cause: ObligationCause<'tcx>,
246 ) -> Normalized<'tcx, T>
248 T: TypeFoldable<'tcx>,
250 let mut obligations = Vec::new();
251 let value = normalize_with_depth_to(selcx, param_env, cause, depth, value, &mut obligations);
252 Normalized { value, obligations }
255 pub fn normalize_with_depth_to<'a, 'b, 'tcx, T>(
256 selcx: &'a mut SelectionContext<'b, 'tcx>,
257 param_env: ty::ParamEnv<'tcx>,
258 cause: ObligationCause<'tcx>,
261 obligations: &mut Vec<PredicateObligation<'tcx>>,
264 T: TypeFoldable<'tcx>,
266 debug!("normalize_with_depth(depth={}, value={:?})", depth, value);
267 let mut normalizer = AssocTypeNormalizer::new(selcx, param_env, cause, depth, obligations);
268 let result = ensure_sufficient_stack(|| normalizer.fold(value));
270 "normalize_with_depth: depth={} result={:?} with {} obligations",
273 normalizer.obligations.len()
275 debug!("normalize_with_depth: depth={} obligations={:?}", depth, normalizer.obligations);
279 struct AssocTypeNormalizer<'a, 'b, 'tcx> {
280 selcx: &'a mut SelectionContext<'b, 'tcx>,
281 param_env: ty::ParamEnv<'tcx>,
282 cause: ObligationCause<'tcx>,
283 obligations: &'a mut Vec<PredicateObligation<'tcx>>,
287 impl<'a, 'b, 'tcx> AssocTypeNormalizer<'a, 'b, 'tcx> {
289 selcx: &'a mut SelectionContext<'b, 'tcx>,
290 param_env: ty::ParamEnv<'tcx>,
291 cause: ObligationCause<'tcx>,
293 obligations: &'a mut Vec<PredicateObligation<'tcx>>,
294 ) -> AssocTypeNormalizer<'a, 'b, 'tcx> {
295 AssocTypeNormalizer { selcx, param_env, cause, obligations, depth }
298 fn fold<T: TypeFoldable<'tcx>>(&mut self, value: &T) -> T {
299 let value = self.selcx.infcx().resolve_vars_if_possible(value);
301 if !value.has_projections() { value } else { value.fold_with(self) }
305 impl<'a, 'b, 'tcx> TypeFolder<'tcx> for AssocTypeNormalizer<'a, 'b, 'tcx> {
306 fn tcx<'c>(&'c self) -> TyCtxt<'tcx> {
310 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
311 if !ty.has_projections() {
314 // We don't want to normalize associated types that occur inside of region
315 // binders, because they may contain bound regions, and we can't cope with that.
319 // for<'a> fn(<T as Foo<&'a>>::A)
321 // Instead of normalizing `<T as Foo<&'a>>::A` here, we'll
322 // normalize it when we instantiate those bound regions (which
323 // should occur eventually).
325 let ty = ty.super_fold_with(self);
327 ty::Opaque(def_id, substs) if !substs.has_escaping_bound_vars() => {
329 // Only normalize `impl Trait` after type-checking, usually in codegen.
330 match self.param_env.reveal() {
331 Reveal::UserFacing => ty,
334 let recursion_limit = self.tcx().sess.recursion_limit();
335 if !recursion_limit.value_within_limit(self.depth) {
336 let obligation = Obligation::with_depth(
342 self.selcx.infcx().report_overflow_error(&obligation, true);
345 let generic_ty = self.tcx().type_of(def_id);
346 let concrete_ty = generic_ty.subst(self.tcx(), substs);
348 let folded_ty = self.fold_ty(concrete_ty);
355 ty::Projection(ref data) if !data.has_escaping_bound_vars() => {
358 // (*) This is kind of hacky -- we need to be able to
359 // handle normalization within binders because
360 // otherwise we wind up a need to normalize when doing
361 // trait matching (since you can have a trait
362 // obligation like `for<'a> T::B: Fn(&'a i32)`), but
363 // we can't normalize with bound regions in scope. So
364 // far now we just ignore binders but only normalize
365 // if all bound regions are gone (and then we still
366 // have to renormalize whenever we instantiate a
367 // binder). It would be better to normalize in a
368 // binding-aware fashion.
370 let normalized_ty = normalize_projection_type(
376 &mut self.obligations,
379 "AssocTypeNormalizer: depth={} normalized {:?} to {:?}, \
380 now with {} obligations",
384 self.obligations.len()
393 fn fold_const(&mut self, constant: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
394 if self.selcx.tcx().lazy_normalization() {
397 let constant = constant.super_fold_with(self);
398 constant.eval(self.selcx.tcx(), self.param_env)
403 /// The guts of `normalize`: normalize a specific projection like `<T
404 /// as Trait>::Item`. The result is always a type (and possibly
405 /// additional obligations). If ambiguity arises, which implies that
406 /// there are unresolved type variables in the projection, we will
407 /// substitute a fresh type variable `$X` and generate a new
408 /// obligation `<T as Trait>::Item == $X` for later.
409 pub fn normalize_projection_type<'a, 'b, 'tcx>(
410 selcx: &'a mut SelectionContext<'b, 'tcx>,
411 param_env: ty::ParamEnv<'tcx>,
412 projection_ty: ty::ProjectionTy<'tcx>,
413 cause: ObligationCause<'tcx>,
415 obligations: &mut Vec<PredicateObligation<'tcx>>,
417 opt_normalize_projection_type(
425 .unwrap_or_else(move || {
426 // if we bottom out in ambiguity, create a type variable
427 // and a deferred predicate to resolve this when more type
428 // information is available.
430 let tcx = selcx.infcx().tcx;
431 let def_id = projection_ty.item_def_id;
432 let ty_var = selcx.infcx().next_ty_var(TypeVariableOrigin {
433 kind: TypeVariableOriginKind::NormalizeProjectionType,
434 span: tcx.def_span(def_id),
436 let projection = ty::Binder::dummy(ty::ProjectionPredicate { projection_ty, ty: ty_var });
438 Obligation::with_depth(cause, depth + 1, param_env, projection.to_predicate(tcx));
439 obligations.push(obligation);
444 /// The guts of `normalize`: normalize a specific projection like `<T
445 /// as Trait>::Item`. The result is always a type (and possibly
446 /// additional obligations). Returns `None` in the case of ambiguity,
447 /// which indicates that there are unbound type variables.
449 /// This function used to return `Option<NormalizedTy<'tcx>>`, which contains a
450 /// `Ty<'tcx>` and an obligations vector. But that obligation vector was very
451 /// often immediately appended to another obligations vector. So now this
452 /// function takes an obligations vector and appends to it directly, which is
453 /// slightly uglier but avoids the need for an extra short-lived allocation.
454 fn opt_normalize_projection_type<'a, 'b, 'tcx>(
455 selcx: &'a mut SelectionContext<'b, 'tcx>,
456 param_env: ty::ParamEnv<'tcx>,
457 projection_ty: ty::ProjectionTy<'tcx>,
458 cause: ObligationCause<'tcx>,
460 obligations: &mut Vec<PredicateObligation<'tcx>>,
461 ) -> Option<Ty<'tcx>> {
462 let infcx = selcx.infcx();
464 let projection_ty = infcx.resolve_vars_if_possible(&projection_ty);
465 let cache_key = ProjectionCacheKey::new(projection_ty);
468 "opt_normalize_projection_type(\
469 projection_ty={:?}, \
474 // FIXME(#20304) For now, I am caching here, which is good, but it
475 // means we don't capture the type variables that are created in
476 // the case of ambiguity. Which means we may create a large stream
477 // of such variables. OTOH, if we move the caching up a level, we
478 // would not benefit from caching when proving `T: Trait<U=Foo>`
479 // bounds. It might be the case that we want two distinct caches,
480 // or else another kind of cache entry.
482 let cache_result = infcx.inner.borrow_mut().projection_cache().try_start(cache_key);
485 Err(ProjectionCacheEntry::Ambiguous) => {
486 // If we found ambiguity the last time, that means we will continue
487 // to do so until some type in the key changes (and we know it
488 // hasn't, because we just fully resolved it).
490 "opt_normalize_projection_type: \
491 found cache entry: ambiguous"
495 Err(ProjectionCacheEntry::InProgress) => {
496 // If while normalized A::B, we are asked to normalize
497 // A::B, just return A::B itself. This is a conservative
498 // answer, in the sense that A::B *is* clearly equivalent
499 // to A::B, though there may be a better value we can
502 // Under lazy normalization, this can arise when
503 // bootstrapping. That is, imagine an environment with a
504 // where-clause like `A::B == u32`. Now, if we are asked
505 // to normalize `A::B`, we will want to check the
506 // where-clauses in scope. So we will try to unify `A::B`
507 // with `A::B`, which can trigger a recursive
508 // normalization. In that case, I think we will want this code:
511 // let ty = selcx.tcx().mk_projection(projection_ty.item_def_id,
512 // projection_ty.substs;
513 // return Some(NormalizedTy { value: v, obligations: vec![] });
517 "opt_normalize_projection_type: \
518 found cache entry: in-progress"
521 // But for now, let's classify this as an overflow:
522 let recursion_limit = selcx.tcx().sess.recursion_limit();
524 Obligation::with_depth(cause, recursion_limit.0, param_env, projection_ty);
525 selcx.infcx().report_overflow_error(&obligation, false);
527 Err(ProjectionCacheEntry::NormalizedTy(ty)) => {
528 // This is the hottest path in this function.
530 // If we find the value in the cache, then return it along
531 // with the obligations that went along with it. Note
532 // that, when using a fulfillment context, these
533 // obligations could in principle be ignored: they have
534 // already been registered when the cache entry was
535 // created (and hence the new ones will quickly be
536 // discarded as duplicated). But when doing trait
537 // evaluation this is not the case, and dropping the trait
538 // evaluations can causes ICEs (e.g., #43132).
540 "opt_normalize_projection_type: \
541 found normalized ty `{:?}`",
545 // Once we have inferred everything we need to know, we
546 // can ignore the `obligations` from that point on.
547 if infcx.unresolved_type_vars(&ty.value).is_none() {
548 infcx.inner.borrow_mut().projection_cache().complete_normalized(cache_key, &ty);
549 // No need to extend `obligations`.
551 obligations.extend(ty.obligations);
554 obligations.push(get_paranoid_cache_value_obligation(
561 return Some(ty.value);
563 Err(ProjectionCacheEntry::Error) => {
565 "opt_normalize_projection_type: \
568 let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth);
569 obligations.extend(result.obligations);
570 return Some(result.value);
574 let obligation = Obligation::with_depth(cause.clone(), depth, param_env, projection_ty);
575 match project_type(selcx, &obligation) {
576 Ok(ProjectedTy::Progress(Progress {
578 obligations: mut projected_obligations,
580 // if projection succeeded, then what we get out of this
581 // is also non-normalized (consider: it was derived from
582 // an impl, where-clause etc) and hence we must
586 "opt_normalize_projection_type: \
589 projected_obligations={:?}",
590 projected_ty, depth, projected_obligations
593 let result = if projected_ty.has_projections() {
594 let mut normalizer = AssocTypeNormalizer::new(
599 &mut projected_obligations,
601 let normalized_ty = normalizer.fold(&projected_ty);
604 "opt_normalize_projection_type: \
605 normalized_ty={:?} depth={}",
609 Normalized { value: normalized_ty, obligations: projected_obligations }
611 Normalized { value: projected_ty, obligations: projected_obligations }
614 let cache_value = prune_cache_value_obligations(infcx, &result);
615 infcx.inner.borrow_mut().projection_cache().insert_ty(cache_key, cache_value);
616 obligations.extend(result.obligations);
619 Ok(ProjectedTy::NoProgress(projected_ty)) => {
621 "opt_normalize_projection_type: \
622 projected_ty={:?} no progress",
625 let result = Normalized { value: projected_ty, obligations: vec![] };
626 infcx.inner.borrow_mut().projection_cache().insert_ty(cache_key, result.clone());
627 // No need to extend `obligations`.
630 Err(ProjectionTyError::TooManyCandidates) => {
632 "opt_normalize_projection_type: \
635 infcx.inner.borrow_mut().projection_cache().ambiguous(cache_key);
638 Err(ProjectionTyError::TraitSelectionError(_)) => {
639 debug!("opt_normalize_projection_type: ERROR");
640 // if we got an error processing the `T as Trait` part,
641 // just return `ty::err` but add the obligation `T :
642 // Trait`, which when processed will cause the error to be
645 infcx.inner.borrow_mut().projection_cache().error(cache_key);
646 let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth);
647 obligations.extend(result.obligations);
653 /// If there are unresolved type variables, then we need to include
654 /// any subobligations that bind them, at least until those type
655 /// variables are fully resolved.
656 fn prune_cache_value_obligations<'a, 'tcx>(
657 infcx: &'a InferCtxt<'a, 'tcx>,
658 result: &NormalizedTy<'tcx>,
659 ) -> NormalizedTy<'tcx> {
660 if infcx.unresolved_type_vars(&result.value).is_none() {
661 return NormalizedTy { value: result.value, obligations: vec![] };
664 let mut obligations: Vec<_> = result
667 .filter(|obligation| {
668 match obligation.predicate.skip_binders() {
669 // We found a `T: Foo<X = U>` predicate, let's check
670 // if `U` references any unresolved type
671 // variables. In principle, we only care if this
672 // projection can help resolve any of the type
673 // variables found in `result.value` -- but we just
674 // check for any type variables here, for fear of
675 // indirect obligations (e.g., we project to `?0`,
676 // but we have `T: Foo<X = ?1>` and `?1: Bar<X =
678 ty::PredicateAtom::Projection(data) => {
679 infcx.unresolved_type_vars(&ty::Binder::bind(data.ty)).is_some()
682 // We are only interested in `T: Foo<X = U>` predicates, whre
683 // `U` references one of `unresolved_type_vars`. =)
690 obligations.shrink_to_fit();
692 NormalizedTy { value: result.value, obligations }
695 /// Whenever we give back a cache result for a projection like `<T as
696 /// Trait>::Item ==> X`, we *always* include the obligation to prove
697 /// that `T: Trait` (we may also include some other obligations). This
698 /// may or may not be necessary -- in principle, all the obligations
699 /// that must be proven to show that `T: Trait` were also returned
700 /// when the cache was first populated. But there are some vague concerns,
701 /// and so we take the precautionary measure of including `T: Trait` in
704 /// Concern #1. The current setup is fragile. Perhaps someone could
705 /// have failed to prove the concerns from when the cache was
706 /// populated, but also not have used a snapshot, in which case the
707 /// cache could remain populated even though `T: Trait` has not been
708 /// shown. In this case, the "other code" is at fault -- when you
709 /// project something, you are supposed to either have a snapshot or
710 /// else prove all the resulting obligations -- but it's still easy to
713 /// Concern #2. Even within the snapshot, if those original
714 /// obligations are not yet proven, then we are able to do projections
715 /// that may yet turn out to be wrong. This *may* lead to some sort
716 /// of trouble, though we don't have a concrete example of how that
717 /// can occur yet. But it seems risky at best.
718 fn get_paranoid_cache_value_obligation<'a, 'tcx>(
719 infcx: &'a InferCtxt<'a, 'tcx>,
720 param_env: ty::ParamEnv<'tcx>,
721 projection_ty: ty::ProjectionTy<'tcx>,
722 cause: ObligationCause<'tcx>,
724 ) -> PredicateObligation<'tcx> {
725 let trait_ref = projection_ty.trait_ref(infcx.tcx).to_poly_trait_ref();
728 recursion_depth: depth,
730 predicate: trait_ref.without_const().to_predicate(infcx.tcx),
734 /// If we are projecting `<T as Trait>::Item`, but `T: Trait` does not
735 /// hold. In various error cases, we cannot generate a valid
736 /// normalized projection. Therefore, we create an inference variable
737 /// return an associated obligation that, when fulfilled, will lead to
740 /// Note that we used to return `Error` here, but that was quite
741 /// dubious -- the premise was that an error would *eventually* be
742 /// reported, when the obligation was processed. But in general once
743 /// you see a `Error` you are supposed to be able to assume that an
744 /// error *has been* reported, so that you can take whatever heuristic
745 /// paths you want to take. To make things worse, it was possible for
746 /// cycles to arise, where you basically had a setup like `<MyType<$0>
747 /// as Trait>::Foo == $0`. Here, normalizing `<MyType<$0> as
748 /// Trait>::Foo> to `[type error]` would lead to an obligation of
749 /// `<MyType<[type error]> as Trait>::Foo`. We are supposed to report
750 /// an error for this obligation, but we legitimately should not,
751 /// because it contains `[type error]`. Yuck! (See issue #29857 for
752 /// one case where this arose.)
753 fn normalize_to_error<'a, 'tcx>(
754 selcx: &mut SelectionContext<'a, 'tcx>,
755 param_env: ty::ParamEnv<'tcx>,
756 projection_ty: ty::ProjectionTy<'tcx>,
757 cause: ObligationCause<'tcx>,
759 ) -> NormalizedTy<'tcx> {
760 let trait_ref = projection_ty.trait_ref(selcx.tcx()).to_poly_trait_ref();
761 let trait_obligation = Obligation {
763 recursion_depth: depth,
765 predicate: trait_ref.without_const().to_predicate(selcx.tcx()),
767 let tcx = selcx.infcx().tcx;
768 let def_id = projection_ty.item_def_id;
769 let new_value = selcx.infcx().next_ty_var(TypeVariableOrigin {
770 kind: TypeVariableOriginKind::NormalizeProjectionType,
771 span: tcx.def_span(def_id),
773 Normalized { value: new_value, obligations: vec![trait_obligation] }
776 enum ProjectedTy<'tcx> {
777 Progress(Progress<'tcx>),
778 NoProgress(Ty<'tcx>),
781 struct Progress<'tcx> {
783 obligations: Vec<PredicateObligation<'tcx>>,
786 impl<'tcx> Progress<'tcx> {
787 fn error(tcx: TyCtxt<'tcx>) -> Self {
788 Progress { ty: tcx.ty_error(), obligations: vec![] }
791 fn with_addl_obligations(mut self, mut obligations: Vec<PredicateObligation<'tcx>>) -> Self {
793 "with_addl_obligations: self.obligations.len={} obligations.len={}",
794 self.obligations.len(),
799 "with_addl_obligations: self.obligations={:?} obligations={:?}",
800 self.obligations, obligations
803 self.obligations.append(&mut obligations);
808 /// Computes the result of a projection type (if we can).
811 /// - `obligation` must be fully normalized
812 fn project_type<'cx, 'tcx>(
813 selcx: &mut SelectionContext<'cx, 'tcx>,
814 obligation: &ProjectionTyObligation<'tcx>,
815 ) -> Result<ProjectedTy<'tcx>, ProjectionTyError<'tcx>> {
816 debug!("project(obligation={:?})", obligation);
818 if !selcx.tcx().sess.recursion_limit().value_within_limit(obligation.recursion_depth) {
819 debug!("project: overflow!");
820 return Err(ProjectionTyError::TraitSelectionError(SelectionError::Overflow));
823 let obligation_trait_ref = &obligation.predicate.trait_ref(selcx.tcx());
825 debug!("project: obligation_trait_ref={:?}", obligation_trait_ref);
827 if obligation_trait_ref.references_error() {
828 return Ok(ProjectedTy::Progress(Progress::error(selcx.tcx())));
831 let mut candidates = ProjectionTyCandidateSet::None;
833 // Make sure that the following procedures are kept in order. ParamEnv
834 // needs to be first because it has highest priority, and Select checks
835 // the return value of push_candidate which assumes it's ran at last.
836 assemble_candidates_from_param_env(selcx, obligation, &obligation_trait_ref, &mut candidates);
838 assemble_candidates_from_trait_def(selcx, obligation, &obligation_trait_ref, &mut candidates);
840 assemble_candidates_from_impls(selcx, obligation, &obligation_trait_ref, &mut candidates);
843 ProjectionTyCandidateSet::Single(candidate) => Ok(ProjectedTy::Progress(
844 confirm_candidate(selcx, obligation, &obligation_trait_ref, candidate),
846 ProjectionTyCandidateSet::None => Ok(ProjectedTy::NoProgress(
849 .mk_projection(obligation.predicate.item_def_id, obligation.predicate.substs),
851 // Error occurred while trying to processing impls.
852 ProjectionTyCandidateSet::Error(e) => Err(ProjectionTyError::TraitSelectionError(e)),
853 // Inherent ambiguity that prevents us from even enumerating the
855 ProjectionTyCandidateSet::Ambiguous => Err(ProjectionTyError::TooManyCandidates),
859 /// The first thing we have to do is scan through the parameter
860 /// environment to see whether there are any projection predicates
861 /// there that can answer this question.
862 fn assemble_candidates_from_param_env<'cx, 'tcx>(
863 selcx: &mut SelectionContext<'cx, 'tcx>,
864 obligation: &ProjectionTyObligation<'tcx>,
865 obligation_trait_ref: &ty::TraitRef<'tcx>,
866 candidate_set: &mut ProjectionTyCandidateSet<'tcx>,
868 debug!("assemble_candidates_from_param_env(..)");
869 assemble_candidates_from_predicates(
872 obligation_trait_ref,
874 ProjectionTyCandidate::ParamEnv,
875 obligation.param_env.caller_bounds().iter(),
879 /// In the case of a nested projection like <<A as Foo>::FooT as Bar>::BarT, we may find
880 /// that the definition of `Foo` has some clues:
884 /// type FooT : Bar<BarT=i32>
888 /// Here, for example, we could conclude that the result is `i32`.
889 fn assemble_candidates_from_trait_def<'cx, 'tcx>(
890 selcx: &mut SelectionContext<'cx, 'tcx>,
891 obligation: &ProjectionTyObligation<'tcx>,
892 obligation_trait_ref: &ty::TraitRef<'tcx>,
893 candidate_set: &mut ProjectionTyCandidateSet<'tcx>,
895 debug!("assemble_candidates_from_trait_def(..)");
897 let tcx = selcx.tcx();
898 // Check whether the self-type is itself a projection.
899 // If so, extract what we know from the trait and try to come up with a good answer.
900 let bounds = match obligation_trait_ref.self_ty().kind {
901 ty::Projection(ref data) => {
902 tcx.projection_predicates(data.item_def_id).subst(tcx, data.substs)
904 ty::Opaque(def_id, substs) => tcx.projection_predicates(def_id).subst(tcx, substs),
905 ty::Infer(ty::TyVar(_)) => {
906 // If the self-type is an inference variable, then it MAY wind up
907 // being a projected type, so induce an ambiguity.
908 candidate_set.mark_ambiguous();
914 assemble_candidates_from_predicates(
917 obligation_trait_ref,
919 ProjectionTyCandidate::TraitDef,
924 fn assemble_candidates_from_predicates<'cx, 'tcx>(
925 selcx: &mut SelectionContext<'cx, 'tcx>,
926 obligation: &ProjectionTyObligation<'tcx>,
927 obligation_trait_ref: &ty::TraitRef<'tcx>,
928 candidate_set: &mut ProjectionTyCandidateSet<'tcx>,
929 ctor: fn(ty::PolyProjectionPredicate<'tcx>) -> ProjectionTyCandidate<'tcx>,
930 env_predicates: impl Iterator<Item = ty::Predicate<'tcx>>,
932 debug!("assemble_candidates_from_predicates(obligation={:?})", obligation);
933 let infcx = selcx.infcx();
934 for predicate in env_predicates {
935 debug!("assemble_candidates_from_predicates: predicate={:?}", predicate);
936 if let ty::PredicateAtom::Projection(data) = predicate.skip_binders() {
937 let data = ty::Binder::bind(data);
938 let same_def_id = data.projection_def_id() == obligation.predicate.item_def_id;
940 let is_match = same_def_id
942 let data_poly_trait_ref = data.to_poly_trait_ref(infcx.tcx);
943 let obligation_poly_trait_ref = obligation_trait_ref.to_poly_trait_ref();
945 .at(&obligation.cause, obligation.param_env)
946 .sup(obligation_poly_trait_ref, data_poly_trait_ref)
947 .map(|InferOk { obligations: _, value: () }| {
948 // FIXME(#32730) -- do we need to take obligations
949 // into account in any way? At the moment, no.
955 "assemble_candidates_from_predicates: candidate={:?} \
956 is_match={} same_def_id={}",
957 data, is_match, same_def_id
961 candidate_set.push_candidate(ctor(data));
967 fn assemble_candidates_from_impls<'cx, 'tcx>(
968 selcx: &mut SelectionContext<'cx, 'tcx>,
969 obligation: &ProjectionTyObligation<'tcx>,
970 obligation_trait_ref: &ty::TraitRef<'tcx>,
971 candidate_set: &mut ProjectionTyCandidateSet<'tcx>,
973 // If we are resolving `<T as TraitRef<...>>::Item == Type`,
974 // start out by selecting the predicate `T as TraitRef<...>`:
975 let poly_trait_ref = obligation_trait_ref.to_poly_trait_ref();
976 let trait_obligation = obligation.with(poly_trait_ref.to_poly_trait_predicate());
977 let _ = selcx.infcx().commit_if_ok(|_| {
978 let impl_source = match selcx.select(&trait_obligation) {
979 Ok(Some(impl_source)) => impl_source,
981 candidate_set.mark_ambiguous();
985 debug!("assemble_candidates_from_impls: selection error {:?}", e);
986 candidate_set.mark_error(e);
991 let eligible = match &impl_source {
992 super::ImplSourceClosure(_)
993 | super::ImplSourceGenerator(_)
994 | super::ImplSourceFnPointer(_)
995 | super::ImplSourceObject(_)
996 | super::ImplSourceTraitAlias(_) => {
997 debug!("assemble_candidates_from_impls: impl_source={:?}", impl_source);
1000 super::ImplSourceUserDefined(impl_data) => {
1001 // We have to be careful when projecting out of an
1002 // impl because of specialization. If we are not in
1003 // codegen (i.e., projection mode is not "any"), and the
1004 // impl's type is declared as default, then we disable
1005 // projection (even if the trait ref is fully
1006 // monomorphic). In the case where trait ref is not
1007 // fully monomorphic (i.e., includes type parameters),
1008 // this is because those type parameters may
1009 // ultimately be bound to types from other crates that
1010 // may have specialized impls we can't see. In the
1011 // case where the trait ref IS fully monomorphic, this
1012 // is a policy decision that we made in the RFC in
1013 // order to preserve flexibility for the crate that
1014 // defined the specializable impl to specialize later
1015 // for existing types.
1017 // In either case, we handle this by not adding a
1018 // candidate for an impl if it contains a `default`
1021 // NOTE: This should be kept in sync with the similar code in
1022 // `rustc_ty::instance::resolve_associated_item()`.
1024 assoc_ty_def(selcx, impl_data.impl_def_id, obligation.predicate.item_def_id)
1025 .map_err(|ErrorReported| ())?;
1027 if node_item.is_final() {
1028 // Non-specializable items are always projectable.
1031 // Only reveal a specializable default if we're past type-checking
1032 // and the obligation is monomorphic, otherwise passes such as
1033 // transmute checking and polymorphic MIR optimizations could
1034 // get a result which isn't correct for all monomorphizations.
1035 if obligation.param_env.reveal() == Reveal::All {
1036 // NOTE(eddyb) inference variables can resolve to parameters, so
1037 // assume `poly_trait_ref` isn't monomorphic, if it contains any.
1038 let poly_trait_ref =
1039 selcx.infcx().resolve_vars_if_possible(&poly_trait_ref);
1040 !poly_trait_ref.still_further_specializable()
1043 "assemble_candidates_from_impls: not eligible due to default: \
1044 assoc_ty={} predicate={}",
1045 selcx.tcx().def_path_str(node_item.item.def_id),
1046 obligation.predicate,
1052 super::ImplSourceDiscriminantKind(..) => {
1053 // While `DiscriminantKind` is automatically implemented for every type,
1054 // the concrete discriminant may not be known yet.
1056 // Any type with multiple potential discriminant types is therefore not eligible.
1057 let self_ty = selcx.infcx().shallow_resolve(obligation.predicate.self_ty());
1059 match self_ty.kind {
1077 | ty::GeneratorWitness(..)
1080 // Integers and floats always have `u8` as their discriminant.
1081 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(..)) => true,
1087 | ty::Placeholder(..)
1089 | ty::Error(_) => false,
1092 super::ImplSourceParam(..) => {
1093 // This case tell us nothing about the value of an
1094 // associated type. Consider:
1097 // trait SomeTrait { type Foo; }
1098 // fn foo<T:SomeTrait>(...) { }
1101 // If the user writes `<T as SomeTrait>::Foo`, then the `T
1102 // : SomeTrait` binding does not help us decide what the
1103 // type `Foo` is (at least, not more specifically than
1104 // what we already knew).
1106 // But wait, you say! What about an example like this:
1109 // fn bar<T:SomeTrait<Foo=usize>>(...) { ... }
1112 // Doesn't the `T : Sometrait<Foo=usize>` predicate help
1113 // resolve `T::Foo`? And of course it does, but in fact
1114 // that single predicate is desugared into two predicates
1115 // in the compiler: a trait predicate (`T : SomeTrait`) and a
1116 // projection. And the projection where clause is handled
1117 // in `assemble_candidates_from_param_env`.
1120 super::ImplSourceAutoImpl(..) | super::ImplSourceBuiltin(..) => {
1121 // These traits have no associated types.
1123 obligation.cause.span,
1124 "Cannot project an associated type from `{:?}`",
1131 if candidate_set.push_candidate(ProjectionTyCandidate::Select(impl_source)) {
1142 fn confirm_candidate<'cx, 'tcx>(
1143 selcx: &mut SelectionContext<'cx, 'tcx>,
1144 obligation: &ProjectionTyObligation<'tcx>,
1145 obligation_trait_ref: &ty::TraitRef<'tcx>,
1146 candidate: ProjectionTyCandidate<'tcx>,
1147 ) -> Progress<'tcx> {
1148 debug!("confirm_candidate(candidate={:?}, obligation={:?})", candidate, obligation);
1150 let mut progress = match candidate {
1151 ProjectionTyCandidate::ParamEnv(poly_projection)
1152 | ProjectionTyCandidate::TraitDef(poly_projection) => {
1153 confirm_param_env_candidate(selcx, obligation, poly_projection)
1156 ProjectionTyCandidate::Select(impl_source) => {
1157 confirm_select_candidate(selcx, obligation, obligation_trait_ref, impl_source)
1160 // When checking for cycle during evaluation, we compare predicates with
1161 // "syntactic" equality. Since normalization generally introduces a type
1162 // with new region variables, we need to resolve them to existing variables
1163 // when possible for this to work. See `auto-trait-projection-recursion.rs`
1164 // for a case where this matters.
1165 if progress.ty.has_infer_regions() {
1166 progress.ty = OpportunisticRegionResolver::new(selcx.infcx()).fold_ty(progress.ty);
1171 fn confirm_select_candidate<'cx, 'tcx>(
1172 selcx: &mut SelectionContext<'cx, 'tcx>,
1173 obligation: &ProjectionTyObligation<'tcx>,
1174 obligation_trait_ref: &ty::TraitRef<'tcx>,
1175 impl_source: Selection<'tcx>,
1176 ) -> Progress<'tcx> {
1178 super::ImplSourceUserDefined(data) => confirm_impl_candidate(selcx, obligation, data),
1179 super::ImplSourceGenerator(data) => confirm_generator_candidate(selcx, obligation, data),
1180 super::ImplSourceClosure(data) => confirm_closure_candidate(selcx, obligation, data),
1181 super::ImplSourceFnPointer(data) => confirm_fn_pointer_candidate(selcx, obligation, data),
1182 super::ImplSourceDiscriminantKind(data) => {
1183 confirm_discriminant_kind_candidate(selcx, obligation, data)
1185 super::ImplSourceObject(_) => {
1186 confirm_object_candidate(selcx, obligation, obligation_trait_ref)
1188 super::ImplSourceAutoImpl(..)
1189 | super::ImplSourceParam(..)
1190 | super::ImplSourceBuiltin(..)
1191 | super::ImplSourceTraitAlias(..) =>
1192 // we don't create Select candidates with this kind of resolution
1195 obligation.cause.span,
1196 "Cannot project an associated type from `{:?}`",
1203 fn confirm_object_candidate<'cx, 'tcx>(
1204 selcx: &mut SelectionContext<'cx, 'tcx>,
1205 obligation: &ProjectionTyObligation<'tcx>,
1206 obligation_trait_ref: &ty::TraitRef<'tcx>,
1207 ) -> Progress<'tcx> {
1208 let self_ty = obligation_trait_ref.self_ty();
1209 let object_ty = selcx.infcx().shallow_resolve(self_ty);
1210 debug!("confirm_object_candidate(object_ty={:?})", object_ty);
1211 let data = match object_ty.kind {
1212 ty::Dynamic(ref data, ..) => data,
1214 obligation.cause.span,
1215 "confirm_object_candidate called with non-object: {:?}",
1219 let env_predicates = data
1220 .projection_bounds()
1221 .map(|p| p.with_self_ty(selcx.tcx(), object_ty).to_predicate(selcx.tcx()));
1222 let env_predicate = {
1223 let env_predicates = elaborate_predicates(selcx.tcx(), env_predicates);
1225 // select only those projections that are actually projecting an
1226 // item with the correct name
1228 let env_predicates = env_predicates.filter_map(|o| match o.predicate.skip_binders() {
1229 ty::PredicateAtom::Projection(data)
1230 if data.projection_ty.item_def_id == obligation.predicate.item_def_id =>
1232 Some(ty::Binder::bind(data))
1237 // select those with a relevant trait-ref
1238 let mut env_predicates = env_predicates.filter(|data| {
1239 let data_poly_trait_ref = data.to_poly_trait_ref(selcx.tcx());
1240 let obligation_poly_trait_ref = obligation_trait_ref.to_poly_trait_ref();
1241 selcx.infcx().probe(|_| {
1244 .at(&obligation.cause, obligation.param_env)
1245 .sup(obligation_poly_trait_ref, data_poly_trait_ref)
1250 // select the first matching one; there really ought to be one or
1251 // else the object type is not WF, since an object type should
1252 // include all of its projections explicitly
1253 match env_predicates.next() {
1254 Some(env_predicate) => env_predicate,
1257 "confirm_object_candidate: no env-predicate \
1258 found in object type `{:?}`; ill-formed",
1261 return Progress::error(selcx.tcx());
1266 confirm_param_env_candidate(selcx, obligation, env_predicate)
1269 fn confirm_generator_candidate<'cx, 'tcx>(
1270 selcx: &mut SelectionContext<'cx, 'tcx>,
1271 obligation: &ProjectionTyObligation<'tcx>,
1272 impl_source: ImplSourceGeneratorData<'tcx, PredicateObligation<'tcx>>,
1273 ) -> Progress<'tcx> {
1274 let gen_sig = impl_source.substs.as_generator().poly_sig();
1275 let Normalized { value: gen_sig, obligations } = normalize_with_depth(
1277 obligation.param_env,
1278 obligation.cause.clone(),
1279 obligation.recursion_depth + 1,
1284 "confirm_generator_candidate: obligation={:?},gen_sig={:?},obligations={:?}",
1285 obligation, gen_sig, obligations
1288 let tcx = selcx.tcx();
1290 let gen_def_id = tcx.require_lang_item(GeneratorTraitLangItem, None);
1292 let predicate = super::util::generator_trait_ref_and_outputs(
1295 obligation.predicate.self_ty(),
1298 .map_bound(|(trait_ref, yield_ty, return_ty)| {
1299 let name = tcx.associated_item(obligation.predicate.item_def_id).ident.name;
1300 let ty = if name == sym::Return {
1302 } else if name == sym::Yield {
1308 ty::ProjectionPredicate {
1309 projection_ty: ty::ProjectionTy {
1310 substs: trait_ref.substs,
1311 item_def_id: obligation.predicate.item_def_id,
1317 confirm_param_env_candidate(selcx, obligation, predicate)
1318 .with_addl_obligations(impl_source.nested)
1319 .with_addl_obligations(obligations)
1322 fn confirm_discriminant_kind_candidate<'cx, 'tcx>(
1323 selcx: &mut SelectionContext<'cx, 'tcx>,
1324 obligation: &ProjectionTyObligation<'tcx>,
1325 _: ImplSourceDiscriminantKindData,
1326 ) -> Progress<'tcx> {
1327 let tcx = selcx.tcx();
1329 let self_ty = selcx.infcx().shallow_resolve(obligation.predicate.self_ty());
1330 let substs = tcx.mk_substs([self_ty.into()].iter());
1332 let discriminant_def_id = tcx.require_lang_item(DiscriminantTypeLangItem, None);
1334 let predicate = ty::ProjectionPredicate {
1335 projection_ty: ty::ProjectionTy { substs, item_def_id: discriminant_def_id },
1336 ty: self_ty.discriminant_ty(tcx),
1339 confirm_param_env_candidate(selcx, obligation, ty::Binder::bind(predicate))
1342 fn confirm_fn_pointer_candidate<'cx, 'tcx>(
1343 selcx: &mut SelectionContext<'cx, 'tcx>,
1344 obligation: &ProjectionTyObligation<'tcx>,
1345 fn_pointer_impl_source: ImplSourceFnPointerData<'tcx, PredicateObligation<'tcx>>,
1346 ) -> Progress<'tcx> {
1347 let fn_type = selcx.infcx().shallow_resolve(fn_pointer_impl_source.fn_ty);
1348 let sig = fn_type.fn_sig(selcx.tcx());
1349 let Normalized { value: sig, obligations } = normalize_with_depth(
1351 obligation.param_env,
1352 obligation.cause.clone(),
1353 obligation.recursion_depth + 1,
1357 confirm_callable_candidate(selcx, obligation, sig, util::TupleArgumentsFlag::Yes)
1358 .with_addl_obligations(fn_pointer_impl_source.nested)
1359 .with_addl_obligations(obligations)
1362 fn confirm_closure_candidate<'cx, 'tcx>(
1363 selcx: &mut SelectionContext<'cx, 'tcx>,
1364 obligation: &ProjectionTyObligation<'tcx>,
1365 impl_source: ImplSourceClosureData<'tcx, PredicateObligation<'tcx>>,
1366 ) -> Progress<'tcx> {
1367 let closure_sig = impl_source.substs.as_closure().sig();
1368 let Normalized { value: closure_sig, obligations } = normalize_with_depth(
1370 obligation.param_env,
1371 obligation.cause.clone(),
1372 obligation.recursion_depth + 1,
1377 "confirm_closure_candidate: obligation={:?},closure_sig={:?},obligations={:?}",
1378 obligation, closure_sig, obligations
1381 confirm_callable_candidate(selcx, obligation, closure_sig, util::TupleArgumentsFlag::No)
1382 .with_addl_obligations(impl_source.nested)
1383 .with_addl_obligations(obligations)
1386 fn confirm_callable_candidate<'cx, 'tcx>(
1387 selcx: &mut SelectionContext<'cx, 'tcx>,
1388 obligation: &ProjectionTyObligation<'tcx>,
1389 fn_sig: ty::PolyFnSig<'tcx>,
1390 flag: util::TupleArgumentsFlag,
1391 ) -> Progress<'tcx> {
1392 let tcx = selcx.tcx();
1394 debug!("confirm_callable_candidate({:?},{:?})", obligation, fn_sig);
1396 let fn_once_def_id = tcx.require_lang_item(FnOnceTraitLangItem, None);
1397 let fn_once_output_def_id = tcx.require_lang_item(FnOnceOutputLangItem, None);
1399 let predicate = super::util::closure_trait_ref_and_return_type(
1402 obligation.predicate.self_ty(),
1406 .map_bound(|(trait_ref, ret_type)| ty::ProjectionPredicate {
1407 projection_ty: ty::ProjectionTy {
1408 substs: trait_ref.substs,
1409 item_def_id: fn_once_output_def_id,
1414 confirm_param_env_candidate(selcx, obligation, predicate)
1417 fn confirm_param_env_candidate<'cx, 'tcx>(
1418 selcx: &mut SelectionContext<'cx, 'tcx>,
1419 obligation: &ProjectionTyObligation<'tcx>,
1420 poly_cache_entry: ty::PolyProjectionPredicate<'tcx>,
1421 ) -> Progress<'tcx> {
1422 let infcx = selcx.infcx();
1423 let cause = &obligation.cause;
1424 let param_env = obligation.param_env;
1426 let (cache_entry, _) = infcx.replace_bound_vars_with_fresh_vars(
1428 LateBoundRegionConversionTime::HigherRankedType,
1432 let cache_trait_ref = cache_entry.projection_ty.trait_ref(infcx.tcx);
1433 let obligation_trait_ref = obligation.predicate.trait_ref(infcx.tcx);
1434 match infcx.at(cause, param_env).eq(cache_trait_ref, obligation_trait_ref) {
1435 Ok(InferOk { value: _, obligations }) => Progress { ty: cache_entry.ty, obligations },
1438 "Failed to unify obligation `{:?}` with poly_projection `{:?}`: {:?}",
1439 obligation, poly_cache_entry, e,
1441 debug!("confirm_param_env_candidate: {}", msg);
1442 let err = infcx.tcx.ty_error_with_message(obligation.cause.span, &msg);
1443 Progress { ty: err, obligations: vec![] }
1448 fn confirm_impl_candidate<'cx, 'tcx>(
1449 selcx: &mut SelectionContext<'cx, 'tcx>,
1450 obligation: &ProjectionTyObligation<'tcx>,
1451 impl_impl_source: ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>>,
1452 ) -> Progress<'tcx> {
1453 let tcx = selcx.tcx();
1455 let ImplSourceUserDefinedData { impl_def_id, substs, nested } = impl_impl_source;
1456 let assoc_item_id = obligation.predicate.item_def_id;
1457 let trait_def_id = tcx.trait_id_of_impl(impl_def_id).unwrap();
1459 let param_env = obligation.param_env;
1460 let assoc_ty = match assoc_ty_def(selcx, impl_def_id, assoc_item_id) {
1461 Ok(assoc_ty) => assoc_ty,
1462 Err(ErrorReported) => return Progress { ty: tcx.ty_error(), obligations: nested },
1465 if !assoc_ty.item.defaultness.has_value() {
1466 // This means that the impl is missing a definition for the
1467 // associated type. This error will be reported by the type
1468 // checker method `check_impl_items_against_trait`, so here we
1469 // just return Error.
1471 "confirm_impl_candidate: no associated type {:?} for {:?}",
1472 assoc_ty.item.ident, obligation.predicate
1474 return Progress { ty: tcx.ty_error(), obligations: nested };
1476 // If we're trying to normalize `<Vec<u32> as X>::A<S>` using
1477 //`impl<T> X for Vec<T> { type A<Y> = Box<Y>; }`, then:
1479 // * `obligation.predicate.substs` is `[Vec<u32>, S]`
1480 // * `substs` is `[u32]`
1481 // * `substs` ends up as `[u32, S]`
1482 let substs = obligation.predicate.substs.rebase_onto(tcx, trait_def_id, substs);
1484 translate_substs(selcx.infcx(), param_env, impl_def_id, substs, assoc_ty.defining_node);
1485 let ty = tcx.type_of(assoc_ty.item.def_id);
1486 if substs.len() != tcx.generics_of(assoc_ty.item.def_id).count() {
1487 let err = tcx.ty_error_with_message(
1489 "impl item and trait item have different parameter counts",
1491 Progress { ty: err, obligations: nested }
1493 Progress { ty: ty.subst(tcx, substs), obligations: nested }
1497 /// Locate the definition of an associated type in the specialization hierarchy,
1498 /// starting from the given impl.
1500 /// Based on the "projection mode", this lookup may in fact only examine the
1501 /// topmost impl. See the comments for `Reveal` for more details.
1503 selcx: &SelectionContext<'_, '_>,
1505 assoc_ty_def_id: DefId,
1506 ) -> Result<specialization_graph::LeafDef, ErrorReported> {
1507 let tcx = selcx.tcx();
1508 let assoc_ty_name = tcx.associated_item(assoc_ty_def_id).ident;
1509 let trait_def_id = tcx.impl_trait_ref(impl_def_id).unwrap().def_id;
1510 let trait_def = tcx.trait_def(trait_def_id);
1512 // This function may be called while we are still building the
1513 // specialization graph that is queried below (via TraitDef::ancestors()),
1514 // so, in order to avoid unnecessary infinite recursion, we manually look
1515 // for the associated item at the given impl.
1516 // If there is no such item in that impl, this function will fail with a
1517 // cycle error if the specialization graph is currently being built.
1518 let impl_node = specialization_graph::Node::Impl(impl_def_id);
1519 for item in impl_node.items(tcx) {
1520 if matches!(item.kind, ty::AssocKind::Type)
1521 && tcx.hygienic_eq(item.ident, assoc_ty_name, trait_def_id)
1523 return Ok(specialization_graph::LeafDef {
1525 defining_node: impl_node,
1526 finalizing_node: if item.defaultness.is_default() { None } else { Some(impl_node) },
1531 let ancestors = trait_def.ancestors(tcx, impl_def_id)?;
1532 if let Some(assoc_item) = ancestors.leaf_def(tcx, assoc_ty_name, ty::AssocKind::Type) {
1535 // This is saying that neither the trait nor
1536 // the impl contain a definition for this
1537 // associated type. Normally this situation
1538 // could only arise through a compiler bug --
1539 // if the user wrote a bad item name, it
1540 // should have failed in astconv.
1541 bug!("No associated type `{}` for {}", assoc_ty_name, tcx.def_path_str(impl_def_id))
1545 crate trait ProjectionCacheKeyExt<'tcx>: Sized {
1546 fn from_poly_projection_predicate(
1547 selcx: &mut SelectionContext<'cx, 'tcx>,
1548 predicate: ty::PolyProjectionPredicate<'tcx>,
1552 impl<'tcx> ProjectionCacheKeyExt<'tcx> for ProjectionCacheKey<'tcx> {
1553 fn from_poly_projection_predicate(
1554 selcx: &mut SelectionContext<'cx, 'tcx>,
1555 predicate: ty::PolyProjectionPredicate<'tcx>,
1557 let infcx = selcx.infcx();
1558 // We don't do cross-snapshot caching of obligations with escaping regions,
1559 // so there's no cache key to use
1560 predicate.no_bound_vars().map(|predicate| {
1561 ProjectionCacheKey::new(
1562 // We don't attempt to match up with a specific type-variable state
1563 // from a specific call to `opt_normalize_projection_type` - if
1564 // there's no precise match, the original cache entry is "stranded"
1566 infcx.resolve_vars_if_possible(&predicate.projection_ty),