1 //! Code for projecting associated types out of trait references.
3 use super::specialization_graph;
4 use super::translate_substs;
6 use super::MismatchedProjectionTypes;
8 use super::ObligationCause;
9 use super::PredicateObligation;
11 use super::SelectionContext;
12 use super::SelectionError;
14 ImplSourceClosureData, ImplSourceDiscriminantKindData, ImplSourceFnPointerData,
15 ImplSourceGeneratorData, ImplSourcePointeeData, ImplSourceUserDefinedData,
17 use super::{Normalized, NormalizedTy, ProjectionCacheEntry, ProjectionCacheKey};
19 use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
20 use crate::infer::{InferCtxt, InferOk, LateBoundRegionConversionTime};
21 use crate::traits::error_reporting::InferCtxtExt as _;
22 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
23 use crate::traits::select::ProjectionMatchesProjection;
24 use rustc_data_structures::sso::SsoHashSet;
25 use rustc_data_structures::stack::ensure_sufficient_stack;
26 use rustc_errors::ErrorGuaranteed;
27 use rustc_hir::def::DefKind;
28 use rustc_hir::def_id::DefId;
29 use rustc_hir::lang_items::LangItem;
30 use rustc_infer::infer::resolve::OpportunisticRegionResolver;
31 use rustc_middle::traits::select::OverflowError;
32 use rustc_middle::ty::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable};
33 use rustc_middle::ty::subst::Subst;
34 use rustc_middle::ty::visit::{MaxUniverse, TypeVisitable};
35 use rustc_middle::ty::{self, Term, ToPredicate, Ty, TyCtxt};
36 use rustc_span::symbol::sym;
38 use std::collections::BTreeMap;
40 pub use rustc_middle::traits::Reveal;
42 pub type PolyProjectionObligation<'tcx> = Obligation<'tcx, ty::PolyProjectionPredicate<'tcx>>;
44 pub type ProjectionObligation<'tcx> = Obligation<'tcx, ty::ProjectionPredicate<'tcx>>;
46 pub type ProjectionTyObligation<'tcx> = Obligation<'tcx, ty::ProjectionTy<'tcx>>;
48 pub(super) struct InProgress;
50 /// When attempting to resolve `<T as TraitRef>::Name` ...
52 pub enum ProjectionError<'tcx> {
53 /// ...we found multiple sources of information and couldn't resolve the ambiguity.
56 /// ...an error occurred matching `T : TraitRef`
57 TraitSelectionError(SelectionError<'tcx>),
60 #[derive(PartialEq, Eq, Debug)]
61 enum ProjectionCandidate<'tcx> {
62 /// From a where-clause in the env or object type
63 ParamEnv(ty::PolyProjectionPredicate<'tcx>),
65 /// From the definition of `Trait` when you have something like <<A as Trait>::B as Trait2>::C
66 TraitDef(ty::PolyProjectionPredicate<'tcx>),
68 /// Bounds specified on an object type
69 Object(ty::PolyProjectionPredicate<'tcx>),
71 /// From an "impl" (or a "pseudo-impl" returned by select)
72 Select(Selection<'tcx>),
75 enum ProjectionCandidateSet<'tcx> {
77 Single(ProjectionCandidate<'tcx>),
79 Error(SelectionError<'tcx>),
82 impl<'tcx> ProjectionCandidateSet<'tcx> {
83 fn mark_ambiguous(&mut self) {
84 *self = ProjectionCandidateSet::Ambiguous;
87 fn mark_error(&mut self, err: SelectionError<'tcx>) {
88 *self = ProjectionCandidateSet::Error(err);
91 // Returns true if the push was successful, or false if the candidate
92 // was discarded -- this could be because of ambiguity, or because
93 // a higher-priority candidate is already there.
94 fn push_candidate(&mut self, candidate: ProjectionCandidate<'tcx>) -> bool {
95 use self::ProjectionCandidate::*;
96 use self::ProjectionCandidateSet::*;
98 // This wacky variable is just used to try and
99 // make code readable and avoid confusing paths.
100 // It is assigned a "value" of `()` only on those
101 // paths in which we wish to convert `*self` to
102 // ambiguous (and return false, because the candidate
103 // was not used). On other paths, it is not assigned,
104 // and hence if those paths *could* reach the code that
105 // comes after the match, this fn would not compile.
106 let convert_to_ambiguous;
110 *self = Single(candidate);
115 // Duplicates can happen inside ParamEnv. In the case, we
116 // perform a lazy deduplication.
117 if current == &candidate {
121 // Prefer where-clauses. As in select, if there are multiple
122 // candidates, we prefer where-clause candidates over impls. This
123 // may seem a bit surprising, since impls are the source of
124 // "truth" in some sense, but in fact some of the impls that SEEM
125 // applicable are not, because of nested obligations. Where
126 // clauses are the safer choice. See the comment on
127 // `select::SelectionCandidate` and #21974 for more details.
128 match (current, candidate) {
129 (ParamEnv(..), ParamEnv(..)) => convert_to_ambiguous = (),
130 (ParamEnv(..), _) => return false,
131 (_, ParamEnv(..)) => unreachable!(),
132 (_, _) => convert_to_ambiguous = (),
136 Ambiguous | Error(..) => {
141 // We only ever get here when we moved from a single candidate
143 let () = convert_to_ambiguous;
149 /// States returned from `poly_project_and_unify_type`. Takes the place
150 /// of the old return type, which was:
151 /// ```ignore (not-rust)
153 /// Result<Option<Vec<PredicateObligation<'tcx>>>, InProgress>,
154 /// MismatchedProjectionTypes<'tcx>,
157 pub(super) enum ProjectAndUnifyResult<'tcx> {
158 /// The projection bound holds subject to the given obligations. If the
159 /// projection cannot be normalized because the required trait bound does
160 /// not hold, this is returned, with `obligations` being a predicate that
161 /// cannot be proven.
162 Holds(Vec<PredicateObligation<'tcx>>),
163 /// The projection cannot be normalized due to ambiguity. Resolving some
164 /// inference variables in the projection may fix this.
166 /// The project cannot be normalized because `poly_project_and_unify_type`
167 /// is called recursively while normalizing the same projection.
169 // the projection can be normalized, but is not equal to the expected type.
170 // Returns the type error that arose from the mismatch.
171 MismatchedProjectionTypes(MismatchedProjectionTypes<'tcx>),
174 /// Evaluates constraints of the form:
175 /// ```ignore (not-rust)
176 /// for<...> <T as Trait>::U == V
178 /// If successful, this may result in additional obligations. Also returns
179 /// the projection cache key used to track these additional obligations.
180 #[instrument(level = "debug", skip(selcx))]
181 pub(super) fn poly_project_and_unify_type<'cx, 'tcx>(
182 selcx: &mut SelectionContext<'cx, 'tcx>,
183 obligation: &PolyProjectionObligation<'tcx>,
184 ) -> ProjectAndUnifyResult<'tcx> {
185 let infcx = selcx.infcx();
186 let r = infcx.commit_if_ok(|_snapshot| {
187 let old_universe = infcx.universe();
188 let placeholder_predicate =
189 infcx.replace_bound_vars_with_placeholders(obligation.predicate);
190 let new_universe = infcx.universe();
192 let placeholder_obligation = obligation.with(placeholder_predicate);
193 match project_and_unify_type(selcx, &placeholder_obligation) {
194 ProjectAndUnifyResult::MismatchedProjectionTypes(e) => Err(e),
195 ProjectAndUnifyResult::Holds(obligations)
196 if old_universe != new_universe
197 && selcx.tcx().features().generic_associated_types_extended =>
199 // If the `generic_associated_types_extended` feature is active, then we ignore any
200 // obligations references lifetimes from any universe greater than or equal to the
201 // universe just created. Otherwise, we can end up with something like `for<'a> I: 'a`,
202 // which isn't quite what we want. Ideally, we want either an implied
203 // `for<'a where I: 'a> I: 'a` or we want to "lazily" check these hold when we
204 // substitute concrete regions. There is design work to be done here; until then,
205 // however, this allows experimenting potential GAT features without running into
206 // well-formedness issues.
207 let new_obligations = obligations
209 .filter(|obligation| {
210 let mut visitor = MaxUniverse::new();
211 obligation.predicate.visit_with(&mut visitor);
212 visitor.max_universe() < new_universe
215 Ok(ProjectAndUnifyResult::Holds(new_obligations))
223 Err(err) => ProjectAndUnifyResult::MismatchedProjectionTypes(err),
227 /// Evaluates constraints of the form:
228 /// ```ignore (not-rust)
229 /// <T as Trait>::U == V
231 /// If successful, this may result in additional obligations.
233 /// See [poly_project_and_unify_type] for an explanation of the return value.
234 #[tracing::instrument(level = "debug", skip(selcx))]
235 fn project_and_unify_type<'cx, 'tcx>(
236 selcx: &mut SelectionContext<'cx, 'tcx>,
237 obligation: &ProjectionObligation<'tcx>,
238 ) -> ProjectAndUnifyResult<'tcx> {
239 let mut obligations = vec![];
241 let infcx = selcx.infcx();
242 let normalized = match opt_normalize_projection_type(
244 obligation.param_env,
245 obligation.predicate.projection_ty,
246 obligation.cause.clone(),
247 obligation.recursion_depth,
251 Ok(None) => return ProjectAndUnifyResult::FailedNormalization,
252 Err(InProgress) => return ProjectAndUnifyResult::Recursive,
254 debug!(?normalized, ?obligations, "project_and_unify_type result");
256 .at(&obligation.cause, obligation.param_env)
257 .eq(normalized, obligation.predicate.term)
259 Ok(InferOk { obligations: inferred_obligations, value: () }) => {
260 obligations.extend(inferred_obligations);
261 ProjectAndUnifyResult::Holds(obligations)
264 debug!("equating types encountered error {:?}", err);
265 ProjectAndUnifyResult::MismatchedProjectionTypes(MismatchedProjectionTypes { err })
270 /// Normalizes any associated type projections in `value`, replacing
271 /// them with a fully resolved type where possible. The return value
272 /// combines the normalized result and any additional obligations that
273 /// were incurred as result.
274 pub fn normalize<'a, 'b, 'tcx, T>(
275 selcx: &'a mut SelectionContext<'b, 'tcx>,
276 param_env: ty::ParamEnv<'tcx>,
277 cause: ObligationCause<'tcx>,
279 ) -> Normalized<'tcx, T>
281 T: TypeFoldable<'tcx>,
283 let mut obligations = Vec::new();
284 let value = normalize_to(selcx, param_env, cause, value, &mut obligations);
285 Normalized { value, obligations }
288 pub fn normalize_to<'a, 'b, 'tcx, T>(
289 selcx: &'a mut SelectionContext<'b, 'tcx>,
290 param_env: ty::ParamEnv<'tcx>,
291 cause: ObligationCause<'tcx>,
293 obligations: &mut Vec<PredicateObligation<'tcx>>,
296 T: TypeFoldable<'tcx>,
298 normalize_with_depth_to(selcx, param_env, cause, 0, value, obligations)
301 /// As `normalize`, but with a custom depth.
302 pub fn normalize_with_depth<'a, 'b, 'tcx, T>(
303 selcx: &'a mut SelectionContext<'b, 'tcx>,
304 param_env: ty::ParamEnv<'tcx>,
305 cause: ObligationCause<'tcx>,
308 ) -> Normalized<'tcx, T>
310 T: TypeFoldable<'tcx>,
312 let mut obligations = Vec::new();
313 let value = normalize_with_depth_to(selcx, param_env, cause, depth, value, &mut obligations);
314 Normalized { value, obligations }
317 #[instrument(level = "info", skip(selcx, param_env, cause, obligations))]
318 pub fn normalize_with_depth_to<'a, 'b, 'tcx, T>(
319 selcx: &'a mut SelectionContext<'b, 'tcx>,
320 param_env: ty::ParamEnv<'tcx>,
321 cause: ObligationCause<'tcx>,
324 obligations: &mut Vec<PredicateObligation<'tcx>>,
327 T: TypeFoldable<'tcx>,
329 debug!(obligations.len = obligations.len());
330 let mut normalizer = AssocTypeNormalizer::new(selcx, param_env, cause, depth, obligations);
331 let result = ensure_sufficient_stack(|| normalizer.fold(value));
332 debug!(?result, obligations.len = normalizer.obligations.len());
333 debug!(?normalizer.obligations,);
337 #[instrument(level = "info", skip(selcx, param_env, cause, obligations))]
338 pub fn try_normalize_with_depth_to<'a, 'b, 'tcx, T>(
339 selcx: &'a mut SelectionContext<'b, 'tcx>,
340 param_env: ty::ParamEnv<'tcx>,
341 cause: ObligationCause<'tcx>,
344 obligations: &mut Vec<PredicateObligation<'tcx>>,
347 T: TypeFoldable<'tcx>,
349 debug!(obligations.len = obligations.len());
350 let mut normalizer = AssocTypeNormalizer::new_without_eager_inference_replacement(
357 let result = ensure_sufficient_stack(|| normalizer.fold(value));
358 debug!(?result, obligations.len = normalizer.obligations.len());
359 debug!(?normalizer.obligations,);
363 pub(crate) fn needs_normalization<'tcx, T: TypeVisitable<'tcx>>(value: &T, reveal: Reveal) -> bool {
365 Reveal::UserFacing => value
366 .has_type_flags(ty::TypeFlags::HAS_TY_PROJECTION | ty::TypeFlags::HAS_CT_PROJECTION),
367 Reveal::All => value.has_type_flags(
368 ty::TypeFlags::HAS_TY_PROJECTION
369 | ty::TypeFlags::HAS_TY_OPAQUE
370 | ty::TypeFlags::HAS_CT_PROJECTION,
375 struct AssocTypeNormalizer<'a, 'b, 'tcx> {
376 selcx: &'a mut SelectionContext<'b, 'tcx>,
377 param_env: ty::ParamEnv<'tcx>,
378 cause: ObligationCause<'tcx>,
379 obligations: &'a mut Vec<PredicateObligation<'tcx>>,
381 universes: Vec<Option<ty::UniverseIndex>>,
382 /// If true, when a projection is unable to be completed, an inference
383 /// variable will be created and an obligation registered to project to that
384 /// inference variable. Also, constants will be eagerly evaluated.
385 eager_inference_replacement: bool,
388 impl<'a, 'b, 'tcx> AssocTypeNormalizer<'a, 'b, 'tcx> {
390 selcx: &'a mut SelectionContext<'b, 'tcx>,
391 param_env: ty::ParamEnv<'tcx>,
392 cause: ObligationCause<'tcx>,
394 obligations: &'a mut Vec<PredicateObligation<'tcx>>,
395 ) -> AssocTypeNormalizer<'a, 'b, 'tcx> {
396 AssocTypeNormalizer {
403 eager_inference_replacement: true,
407 fn new_without_eager_inference_replacement(
408 selcx: &'a mut SelectionContext<'b, 'tcx>,
409 param_env: ty::ParamEnv<'tcx>,
410 cause: ObligationCause<'tcx>,
412 obligations: &'a mut Vec<PredicateObligation<'tcx>>,
413 ) -> AssocTypeNormalizer<'a, 'b, 'tcx> {
414 AssocTypeNormalizer {
421 eager_inference_replacement: false,
425 fn fold<T: TypeFoldable<'tcx>>(&mut self, value: T) -> T {
426 let value = self.selcx.infcx().resolve_vars_if_possible(value);
430 !value.has_escaping_bound_vars(),
431 "Normalizing {:?} without wrapping in a `Binder`",
435 if !needs_normalization(&value, self.param_env.reveal()) {
438 value.fold_with(self)
443 impl<'a, 'b, 'tcx> TypeFolder<'tcx> for AssocTypeNormalizer<'a, 'b, 'tcx> {
444 fn tcx<'c>(&'c self) -> TyCtxt<'tcx> {
448 fn fold_binder<T: TypeFoldable<'tcx>>(
450 t: ty::Binder<'tcx, T>,
451 ) -> ty::Binder<'tcx, T> {
452 self.universes.push(None);
453 let t = t.super_fold_with(self);
454 self.universes.pop();
458 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
459 if !needs_normalization(&ty, self.param_env.reveal()) {
463 // We try to be a little clever here as a performance optimization in
464 // cases where there are nested projections under binders.
467 // for<'a> fn(<T as Foo>::One<'a, Box<dyn Bar<'a, Item=<T as Foo>::Two<'a>>>>)
469 // We normalize the substs on the projection before the projecting, but
470 // if we're naive, we'll
471 // replace bound vars on inner, project inner, replace placeholders on inner,
472 // replace bound vars on outer, project outer, replace placeholders on outer
474 // However, if we're a bit more clever, we can replace the bound vars
475 // on the entire type before normalizing nested projections, meaning we
476 // replace bound vars on outer, project inner,
477 // project outer, replace placeholders on outer
479 // This is possible because the inner `'a` will already be a placeholder
480 // when we need to normalize the inner projection
482 // On the other hand, this does add a bit of complexity, since we only
483 // replace bound vars if the current type is a `Projection` and we need
484 // to make sure we don't forget to fold the substs regardless.
487 // This is really important. While we *can* handle this, this has
488 // severe performance implications for large opaque types with
489 // late-bound regions. See `issue-88862` benchmark.
490 ty::Opaque(def_id, substs) if !substs.has_escaping_bound_vars() => {
491 // Only normalize `impl Trait` outside of type inference, usually in codegen.
492 match self.param_env.reveal() {
493 Reveal::UserFacing => ty.super_fold_with(self),
496 let recursion_limit = self.tcx().recursion_limit();
497 if !recursion_limit.value_within_limit(self.depth) {
498 let obligation = Obligation::with_depth(
504 self.selcx.infcx().report_overflow_error(&obligation, true);
507 let substs = substs.fold_with(self);
508 let generic_ty = self.tcx().bound_type_of(def_id);
509 let concrete_ty = generic_ty.subst(self.tcx(), substs);
511 let folded_ty = self.fold_ty(concrete_ty);
518 ty::Projection(data) if !data.has_escaping_bound_vars() => {
519 // This branch is *mostly* just an optimization: when we don't
520 // have escaping bound vars, we don't need to replace them with
521 // placeholders (see branch below). *Also*, we know that we can
522 // register an obligation to *later* project, since we know
523 // there won't be bound vars there.
524 let data = data.fold_with(self);
525 let normalized_ty = if self.eager_inference_replacement {
526 normalize_projection_type(
532 &mut self.obligations,
535 opt_normalize_projection_type(
541 &mut self.obligations,
545 .unwrap_or_else(|| ty::Term::Ty(ty.super_fold_with(self)))
551 obligations.len = ?self.obligations.len(),
552 "AssocTypeNormalizer: normalized type"
554 normalized_ty.ty().unwrap()
557 ty::Projection(data) => {
558 // If there are escaping bound vars, we temporarily replace the
559 // bound vars with placeholders. Note though, that in the case
560 // that we still can't project for whatever reason (e.g. self
561 // type isn't known enough), we *can't* register an obligation
562 // and return an inference variable (since then that obligation
563 // would have bound vars and that's a can of worms). Instead,
564 // we just give up and fall back to pretending like we never tried!
566 // Note: this isn't necessarily the final approach here; we may
567 // want to figure out how to register obligations with escaping vars
568 // or handle this some other way.
570 let infcx = self.selcx.infcx();
571 let (data, mapped_regions, mapped_types, mapped_consts) =
572 BoundVarReplacer::replace_bound_vars(infcx, &mut self.universes, data);
573 let data = data.fold_with(self);
574 let normalized_ty = opt_normalize_projection_type(
580 &mut self.obligations,
584 .map(|term| term.ty().unwrap())
585 .map(|normalized_ty| {
586 PlaceholderReplacer::replace_placeholders(
595 .unwrap_or_else(|| ty.super_fold_with(self));
601 obligations.len = ?self.obligations.len(),
602 "AssocTypeNormalizer: normalized type"
607 _ => ty.super_fold_with(self),
611 #[instrument(skip(self), level = "debug")]
612 fn fold_const(&mut self, constant: ty::Const<'tcx>) -> ty::Const<'tcx> {
613 if self.selcx.tcx().lazy_normalization() || !self.eager_inference_replacement {
616 let constant = constant.super_fold_with(self);
618 debug!("self.param_env: {:?}", self.param_env);
619 constant.eval(self.selcx.tcx(), self.param_env)
624 fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
625 if p.allow_normalization() && needs_normalization(&p, self.param_env.reveal()) {
626 p.super_fold_with(self)
633 pub struct BoundVarReplacer<'me, 'tcx> {
634 infcx: &'me InferCtxt<'me, 'tcx>,
635 // These three maps track the bound variable that were replaced by placeholders. It might be
636 // nice to remove these since we already have the `kind` in the placeholder; we really just need
637 // the `var` (but we *could* bring that into scope if we were to track them as we pass them).
638 mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
639 mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy>,
640 mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
641 // The current depth relative to *this* folding, *not* the entire normalization. In other words,
642 // the depth of binders we've passed here.
643 current_index: ty::DebruijnIndex,
644 // The `UniverseIndex` of the binding levels above us. These are optional, since we are lazy:
645 // we don't actually create a universe until we see a bound var we have to replace.
646 universe_indices: &'me mut Vec<Option<ty::UniverseIndex>>,
649 impl<'me, 'tcx> BoundVarReplacer<'me, 'tcx> {
650 /// Returns `Some` if we *were* able to replace bound vars. If there are any bound vars that
651 /// use a binding level above `universe_indices.len()`, we fail.
652 pub fn replace_bound_vars<T: TypeFoldable<'tcx>>(
653 infcx: &'me InferCtxt<'me, 'tcx>,
654 universe_indices: &'me mut Vec<Option<ty::UniverseIndex>>,
658 BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
659 BTreeMap<ty::PlaceholderType, ty::BoundTy>,
660 BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
662 let mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion> = BTreeMap::new();
663 let mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy> = BTreeMap::new();
664 let mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar> = BTreeMap::new();
666 let mut replacer = BoundVarReplacer {
671 current_index: ty::INNERMOST,
675 let value = value.fold_with(&mut replacer);
677 (value, replacer.mapped_regions, replacer.mapped_types, replacer.mapped_consts)
680 fn universe_for(&mut self, debruijn: ty::DebruijnIndex) -> ty::UniverseIndex {
681 let infcx = self.infcx;
683 self.universe_indices.len() + self.current_index.as_usize() - debruijn.as_usize() - 1;
684 let universe = self.universe_indices[index].unwrap_or_else(|| {
685 for i in self.universe_indices.iter_mut().take(index + 1) {
686 *i = i.or_else(|| Some(infcx.create_next_universe()))
688 self.universe_indices[index].unwrap()
694 impl<'tcx> TypeFolder<'tcx> for BoundVarReplacer<'_, 'tcx> {
695 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
699 fn fold_binder<T: TypeFoldable<'tcx>>(
701 t: ty::Binder<'tcx, T>,
702 ) -> ty::Binder<'tcx, T> {
703 self.current_index.shift_in(1);
704 let t = t.super_fold_with(self);
705 self.current_index.shift_out(1);
709 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
711 ty::ReLateBound(debruijn, _)
712 if debruijn.as_usize() + 1
713 > self.current_index.as_usize() + self.universe_indices.len() =>
715 bug!("Bound vars outside of `self.universe_indices`");
717 ty::ReLateBound(debruijn, br) if debruijn >= self.current_index => {
718 let universe = self.universe_for(debruijn);
719 let p = ty::PlaceholderRegion { universe, name: br.kind };
720 self.mapped_regions.insert(p, br);
721 self.infcx.tcx.mk_region(ty::RePlaceholder(p))
727 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
729 ty::Bound(debruijn, _)
730 if debruijn.as_usize() + 1
731 > self.current_index.as_usize() + self.universe_indices.len() =>
733 bug!("Bound vars outside of `self.universe_indices`");
735 ty::Bound(debruijn, bound_ty) if debruijn >= self.current_index => {
736 let universe = self.universe_for(debruijn);
737 let p = ty::PlaceholderType { universe, name: bound_ty.var };
738 self.mapped_types.insert(p, bound_ty);
739 self.infcx.tcx.mk_ty(ty::Placeholder(p))
741 _ if t.has_vars_bound_at_or_above(self.current_index) => t.super_fold_with(self),
746 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
748 ty::ConstKind::Bound(debruijn, _)
749 if debruijn.as_usize() + 1
750 > self.current_index.as_usize() + self.universe_indices.len() =>
752 bug!("Bound vars outside of `self.universe_indices`");
754 ty::ConstKind::Bound(debruijn, bound_const) if debruijn >= self.current_index => {
755 let universe = self.universe_for(debruijn);
756 let p = ty::PlaceholderConst { universe, name: bound_const };
757 self.mapped_consts.insert(p, bound_const);
760 .mk_const(ty::ConstS { kind: ty::ConstKind::Placeholder(p), ty: ct.ty() })
762 _ => ct.super_fold_with(self),
766 fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
767 if p.has_vars_bound_at_or_above(self.current_index) { p.super_fold_with(self) } else { p }
771 // The inverse of `BoundVarReplacer`: replaces placeholders with the bound vars from which they came.
772 pub struct PlaceholderReplacer<'me, 'tcx> {
773 infcx: &'me InferCtxt<'me, 'tcx>,
774 mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
775 mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy>,
776 mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
777 universe_indices: &'me [Option<ty::UniverseIndex>],
778 current_index: ty::DebruijnIndex,
781 impl<'me, 'tcx> PlaceholderReplacer<'me, 'tcx> {
782 pub fn replace_placeholders<T: TypeFoldable<'tcx>>(
783 infcx: &'me InferCtxt<'me, 'tcx>,
784 mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
785 mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy>,
786 mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
787 universe_indices: &'me [Option<ty::UniverseIndex>],
790 let mut replacer = PlaceholderReplacer {
796 current_index: ty::INNERMOST,
798 value.fold_with(&mut replacer)
802 impl<'tcx> TypeFolder<'tcx> for PlaceholderReplacer<'_, 'tcx> {
803 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
807 fn fold_binder<T: TypeFoldable<'tcx>>(
809 t: ty::Binder<'tcx, T>,
810 ) -> ty::Binder<'tcx, T> {
811 if !t.has_placeholders() && !t.has_infer_regions() {
814 self.current_index.shift_in(1);
815 let t = t.super_fold_with(self);
816 self.current_index.shift_out(1);
820 fn fold_region(&mut self, r0: ty::Region<'tcx>) -> ty::Region<'tcx> {
826 .unwrap_region_constraints()
827 .opportunistic_resolve_region(self.infcx.tcx, r0),
832 ty::RePlaceholder(p) => {
833 let replace_var = self.mapped_regions.get(&p);
835 Some(replace_var) => {
839 .position(|u| matches!(u, Some(pu) if *pu == p.universe))
840 .unwrap_or_else(|| bug!("Unexpected placeholder universe."));
841 let db = ty::DebruijnIndex::from_usize(
842 self.universe_indices.len() - index + self.current_index.as_usize() - 1,
844 self.tcx().mk_region(ty::ReLateBound(db, *replace_var))
852 debug!(?r0, ?r1, ?r2, "fold_region");
857 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
859 ty::Placeholder(p) => {
860 let replace_var = self.mapped_types.get(&p);
862 Some(replace_var) => {
866 .position(|u| matches!(u, Some(pu) if *pu == p.universe))
867 .unwrap_or_else(|| bug!("Unexpected placeholder universe."));
868 let db = ty::DebruijnIndex::from_usize(
869 self.universe_indices.len() - index + self.current_index.as_usize() - 1,
871 self.tcx().mk_ty(ty::Bound(db, *replace_var))
877 _ if ty.has_placeholders() || ty.has_infer_regions() => ty.super_fold_with(self),
882 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
883 if let ty::ConstKind::Placeholder(p) = ct.kind() {
884 let replace_var = self.mapped_consts.get(&p);
886 Some(replace_var) => {
890 .position(|u| matches!(u, Some(pu) if *pu == p.universe))
891 .unwrap_or_else(|| bug!("Unexpected placeholder universe."));
892 let db = ty::DebruijnIndex::from_usize(
893 self.universe_indices.len() - index + self.current_index.as_usize() - 1,
895 self.tcx().mk_const(ty::ConstS {
896 kind: ty::ConstKind::Bound(db, *replace_var),
903 ct.super_fold_with(self)
908 /// The guts of `normalize`: normalize a specific projection like `<T
909 /// as Trait>::Item`. The result is always a type (and possibly
910 /// additional obligations). If ambiguity arises, which implies that
911 /// there are unresolved type variables in the projection, we will
912 /// substitute a fresh type variable `$X` and generate a new
913 /// obligation `<T as Trait>::Item == $X` for later.
914 pub fn normalize_projection_type<'a, 'b, 'tcx>(
915 selcx: &'a mut SelectionContext<'b, 'tcx>,
916 param_env: ty::ParamEnv<'tcx>,
917 projection_ty: ty::ProjectionTy<'tcx>,
918 cause: ObligationCause<'tcx>,
920 obligations: &mut Vec<PredicateObligation<'tcx>>,
922 opt_normalize_projection_type(
932 .unwrap_or_else(move || {
933 // if we bottom out in ambiguity, create a type variable
934 // and a deferred predicate to resolve this when more type
935 // information is available.
939 .infer_projection(param_env, projection_ty, cause, depth + 1, obligations)
944 /// The guts of `normalize`: normalize a specific projection like `<T
945 /// as Trait>::Item`. The result is always a type (and possibly
946 /// additional obligations). Returns `None` in the case of ambiguity,
947 /// which indicates that there are unbound type variables.
949 /// This function used to return `Option<NormalizedTy<'tcx>>`, which contains a
950 /// `Ty<'tcx>` and an obligations vector. But that obligation vector was very
951 /// often immediately appended to another obligations vector. So now this
952 /// function takes an obligations vector and appends to it directly, which is
953 /// slightly uglier but avoids the need for an extra short-lived allocation.
954 #[instrument(level = "debug", skip(selcx, param_env, cause, obligations))]
955 fn opt_normalize_projection_type<'a, 'b, 'tcx>(
956 selcx: &'a mut SelectionContext<'b, 'tcx>,
957 param_env: ty::ParamEnv<'tcx>,
958 projection_ty: ty::ProjectionTy<'tcx>,
959 cause: ObligationCause<'tcx>,
961 obligations: &mut Vec<PredicateObligation<'tcx>>,
962 ) -> Result<Option<Term<'tcx>>, InProgress> {
963 let infcx = selcx.infcx();
964 // Don't use the projection cache in intercrate mode -
965 // the `infcx` may be re-used between intercrate in non-intercrate
966 // mode, which could lead to using incorrect cache results.
967 let use_cache = !selcx.is_intercrate();
969 let projection_ty = infcx.resolve_vars_if_possible(projection_ty);
970 let cache_key = ProjectionCacheKey::new(projection_ty);
972 // FIXME(#20304) For now, I am caching here, which is good, but it
973 // means we don't capture the type variables that are created in
974 // the case of ambiguity. Which means we may create a large stream
975 // of such variables. OTOH, if we move the caching up a level, we
976 // would not benefit from caching when proving `T: Trait<U=Foo>`
977 // bounds. It might be the case that we want two distinct caches,
978 // or else another kind of cache entry.
980 let cache_result = if use_cache {
981 infcx.inner.borrow_mut().projection_cache().try_start(cache_key)
986 Ok(()) => debug!("no cache"),
987 Err(ProjectionCacheEntry::Ambiguous) => {
988 // If we found ambiguity the last time, that means we will continue
989 // to do so until some type in the key changes (and we know it
990 // hasn't, because we just fully resolved it).
991 debug!("found cache entry: ambiguous");
994 Err(ProjectionCacheEntry::InProgress) => {
995 // Under lazy normalization, this can arise when
996 // bootstrapping. That is, imagine an environment with a
997 // where-clause like `A::B == u32`. Now, if we are asked
998 // to normalize `A::B`, we will want to check the
999 // where-clauses in scope. So we will try to unify `A::B`
1000 // with `A::B`, which can trigger a recursive
1003 debug!("found cache entry: in-progress");
1005 // Cache that normalizing this projection resulted in a cycle. This
1006 // should ensure that, unless this happens within a snapshot that's
1007 // rolled back, fulfillment or evaluation will notice the cycle.
1010 infcx.inner.borrow_mut().projection_cache().recur(cache_key);
1012 return Err(InProgress);
1014 Err(ProjectionCacheEntry::Recur) => {
1015 debug!("recur cache");
1016 return Err(InProgress);
1018 Err(ProjectionCacheEntry::NormalizedTy { ty, complete: _ }) => {
1019 // This is the hottest path in this function.
1021 // If we find the value in the cache, then return it along
1022 // with the obligations that went along with it. Note
1023 // that, when using a fulfillment context, these
1024 // obligations could in principle be ignored: they have
1025 // already been registered when the cache entry was
1026 // created (and hence the new ones will quickly be
1027 // discarded as duplicated). But when doing trait
1028 // evaluation this is not the case, and dropping the trait
1029 // evaluations can causes ICEs (e.g., #43132).
1030 debug!(?ty, "found normalized ty");
1031 obligations.extend(ty.obligations);
1032 return Ok(Some(ty.value));
1034 Err(ProjectionCacheEntry::Error) => {
1035 debug!("opt_normalize_projection_type: found error");
1036 let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth);
1037 obligations.extend(result.obligations);
1038 return Ok(Some(result.value.into()));
1042 let obligation = Obligation::with_depth(cause.clone(), depth, param_env, projection_ty);
1044 match project(selcx, &obligation) {
1045 Ok(Projected::Progress(Progress {
1046 term: projected_term,
1047 obligations: mut projected_obligations,
1049 // if projection succeeded, then what we get out of this
1050 // is also non-normalized (consider: it was derived from
1051 // an impl, where-clause etc) and hence we must
1054 let projected_term = selcx.infcx().resolve_vars_if_possible(projected_term);
1056 let mut result = if projected_term.has_projections() {
1057 let mut normalizer = AssocTypeNormalizer::new(
1062 &mut projected_obligations,
1064 let normalized_ty = normalizer.fold(projected_term);
1066 Normalized { value: normalized_ty, obligations: projected_obligations }
1068 Normalized { value: projected_term, obligations: projected_obligations }
1071 let mut deduped: SsoHashSet<_> = Default::default();
1072 result.obligations.drain_filter(|projected_obligation| {
1073 if !deduped.insert(projected_obligation.clone()) {
1080 infcx.inner.borrow_mut().projection_cache().insert_term(cache_key, result.clone());
1082 obligations.extend(result.obligations);
1083 Ok(Some(result.value))
1085 Ok(Projected::NoProgress(projected_ty)) => {
1086 let result = Normalized { value: projected_ty, obligations: vec![] };
1088 infcx.inner.borrow_mut().projection_cache().insert_term(cache_key, result.clone());
1090 // No need to extend `obligations`.
1091 Ok(Some(result.value))
1093 Err(ProjectionError::TooManyCandidates) => {
1094 debug!("opt_normalize_projection_type: too many candidates");
1096 infcx.inner.borrow_mut().projection_cache().ambiguous(cache_key);
1100 Err(ProjectionError::TraitSelectionError(_)) => {
1101 debug!("opt_normalize_projection_type: ERROR");
1102 // if we got an error processing the `T as Trait` part,
1103 // just return `ty::err` but add the obligation `T :
1104 // Trait`, which when processed will cause the error to be
1108 infcx.inner.borrow_mut().projection_cache().error(cache_key);
1110 let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth);
1111 obligations.extend(result.obligations);
1112 Ok(Some(result.value.into()))
1117 /// If we are projecting `<T as Trait>::Item`, but `T: Trait` does not
1118 /// hold. In various error cases, we cannot generate a valid
1119 /// normalized projection. Therefore, we create an inference variable
1120 /// return an associated obligation that, when fulfilled, will lead to
1123 /// Note that we used to return `Error` here, but that was quite
1124 /// dubious -- the premise was that an error would *eventually* be
1125 /// reported, when the obligation was processed. But in general once
1126 /// you see an `Error` you are supposed to be able to assume that an
1127 /// error *has been* reported, so that you can take whatever heuristic
1128 /// paths you want to take. To make things worse, it was possible for
1129 /// cycles to arise, where you basically had a setup like `<MyType<$0>
1130 /// as Trait>::Foo == $0`. Here, normalizing `<MyType<$0> as
1131 /// Trait>::Foo> to `[type error]` would lead to an obligation of
1132 /// `<MyType<[type error]> as Trait>::Foo`. We are supposed to report
1133 /// an error for this obligation, but we legitimately should not,
1134 /// because it contains `[type error]`. Yuck! (See issue #29857 for
1135 /// one case where this arose.)
1136 fn normalize_to_error<'a, 'tcx>(
1137 selcx: &mut SelectionContext<'a, 'tcx>,
1138 param_env: ty::ParamEnv<'tcx>,
1139 projection_ty: ty::ProjectionTy<'tcx>,
1140 cause: ObligationCause<'tcx>,
1142 ) -> NormalizedTy<'tcx> {
1143 let trait_ref = ty::Binder::dummy(projection_ty.trait_ref(selcx.tcx()));
1144 let trait_obligation = Obligation {
1146 recursion_depth: depth,
1148 predicate: trait_ref.without_const().to_predicate(selcx.tcx()),
1150 let tcx = selcx.infcx().tcx;
1151 let def_id = projection_ty.item_def_id;
1152 let new_value = selcx.infcx().next_ty_var(TypeVariableOrigin {
1153 kind: TypeVariableOriginKind::NormalizeProjectionType,
1154 span: tcx.def_span(def_id),
1156 Normalized { value: new_value, obligations: vec![trait_obligation] }
1159 enum Projected<'tcx> {
1160 Progress(Progress<'tcx>),
1161 NoProgress(ty::Term<'tcx>),
1164 struct Progress<'tcx> {
1165 term: ty::Term<'tcx>,
1166 obligations: Vec<PredicateObligation<'tcx>>,
1169 impl<'tcx> Progress<'tcx> {
1170 fn error(tcx: TyCtxt<'tcx>) -> Self {
1171 Progress { term: tcx.ty_error().into(), obligations: vec![] }
1174 fn with_addl_obligations(mut self, mut obligations: Vec<PredicateObligation<'tcx>>) -> Self {
1175 self.obligations.append(&mut obligations);
1180 /// Computes the result of a projection type (if we can).
1183 /// - `obligation` must be fully normalized
1184 #[tracing::instrument(level = "info", skip(selcx))]
1185 fn project<'cx, 'tcx>(
1186 selcx: &mut SelectionContext<'cx, 'tcx>,
1187 obligation: &ProjectionTyObligation<'tcx>,
1188 ) -> Result<Projected<'tcx>, ProjectionError<'tcx>> {
1189 if !selcx.tcx().recursion_limit().value_within_limit(obligation.recursion_depth) {
1190 // This should really be an immediate error, but some existing code
1191 // relies on being able to recover from this.
1192 return Err(ProjectionError::TraitSelectionError(SelectionError::Overflow(
1193 OverflowError::Canonical,
1197 if obligation.predicate.references_error() {
1198 return Ok(Projected::Progress(Progress::error(selcx.tcx())));
1201 let mut candidates = ProjectionCandidateSet::None;
1203 // Make sure that the following procedures are kept in order. ParamEnv
1204 // needs to be first because it has highest priority, and Select checks
1205 // the return value of push_candidate which assumes it's ran at last.
1206 assemble_candidates_from_param_env(selcx, obligation, &mut candidates);
1208 assemble_candidates_from_trait_def(selcx, obligation, &mut candidates);
1210 assemble_candidates_from_object_ty(selcx, obligation, &mut candidates);
1212 if let ProjectionCandidateSet::Single(ProjectionCandidate::Object(_)) = candidates {
1213 // Avoid normalization cycle from selection (see
1214 // `assemble_candidates_from_object_ty`).
1215 // FIXME(lazy_normalization): Lazy normalization should save us from
1216 // having to special case this.
1218 assemble_candidates_from_impls(selcx, obligation, &mut candidates);
1222 ProjectionCandidateSet::Single(candidate) => {
1223 Ok(Projected::Progress(confirm_candidate(selcx, obligation, candidate)))
1225 ProjectionCandidateSet::None => Ok(Projected::NoProgress(
1226 // FIXME(associated_const_generics): this may need to change in the future?
1227 // need to investigate whether or not this is fine.
1230 .mk_projection(obligation.predicate.item_def_id, obligation.predicate.substs)
1233 // Error occurred while trying to processing impls.
1234 ProjectionCandidateSet::Error(e) => Err(ProjectionError::TraitSelectionError(e)),
1235 // Inherent ambiguity that prevents us from even enumerating the
1237 ProjectionCandidateSet::Ambiguous => Err(ProjectionError::TooManyCandidates),
1241 /// The first thing we have to do is scan through the parameter
1242 /// environment to see whether there are any projection predicates
1243 /// there that can answer this question.
1244 fn assemble_candidates_from_param_env<'cx, 'tcx>(
1245 selcx: &mut SelectionContext<'cx, 'tcx>,
1246 obligation: &ProjectionTyObligation<'tcx>,
1247 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1249 assemble_candidates_from_predicates(
1253 ProjectionCandidate::ParamEnv,
1254 obligation.param_env.caller_bounds().iter(),
1259 /// In the case of a nested projection like <<A as Foo>::FooT as Bar>::BarT, we may find
1260 /// that the definition of `Foo` has some clues:
1262 /// ```ignore (illustrative)
1264 /// type FooT : Bar<BarT=i32>
1268 /// Here, for example, we could conclude that the result is `i32`.
1269 fn assemble_candidates_from_trait_def<'cx, 'tcx>(
1270 selcx: &mut SelectionContext<'cx, 'tcx>,
1271 obligation: &ProjectionTyObligation<'tcx>,
1272 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1274 debug!("assemble_candidates_from_trait_def(..)");
1276 let tcx = selcx.tcx();
1277 // Check whether the self-type is itself a projection.
1278 // If so, extract what we know from the trait and try to come up with a good answer.
1279 let bounds = match *obligation.predicate.self_ty().kind() {
1280 ty::Projection(ref data) => tcx.bound_item_bounds(data.item_def_id).subst(tcx, data.substs),
1281 ty::Opaque(def_id, substs) => tcx.bound_item_bounds(def_id).subst(tcx, substs),
1282 ty::Infer(ty::TyVar(_)) => {
1283 // If the self-type is an inference variable, then it MAY wind up
1284 // being a projected type, so induce an ambiguity.
1285 candidate_set.mark_ambiguous();
1291 assemble_candidates_from_predicates(
1295 ProjectionCandidate::TraitDef,
1301 /// In the case of a trait object like
1302 /// `<dyn Iterator<Item = ()> as Iterator>::Item` we can use the existential
1303 /// predicate in the trait object.
1305 /// We don't go through the select candidate for these bounds to avoid cycles:
1306 /// In the above case, `dyn Iterator<Item = ()>: Iterator` would create a
1307 /// nested obligation of `<dyn Iterator<Item = ()> as Iterator>::Item: Sized`,
1308 /// this then has to be normalized without having to prove
1309 /// `dyn Iterator<Item = ()>: Iterator` again.
1310 fn assemble_candidates_from_object_ty<'cx, 'tcx>(
1311 selcx: &mut SelectionContext<'cx, 'tcx>,
1312 obligation: &ProjectionTyObligation<'tcx>,
1313 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1315 debug!("assemble_candidates_from_object_ty(..)");
1317 let tcx = selcx.tcx();
1319 let self_ty = obligation.predicate.self_ty();
1320 let object_ty = selcx.infcx().shallow_resolve(self_ty);
1321 let data = match object_ty.kind() {
1322 ty::Dynamic(data, ..) => data,
1323 ty::Infer(ty::TyVar(_)) => {
1324 // If the self-type is an inference variable, then it MAY wind up
1325 // being an object type, so induce an ambiguity.
1326 candidate_set.mark_ambiguous();
1331 let env_predicates = data
1332 .projection_bounds()
1333 .filter(|bound| bound.item_def_id() == obligation.predicate.item_def_id)
1334 .map(|p| p.with_self_ty(tcx, object_ty).to_predicate(tcx));
1336 assemble_candidates_from_predicates(
1340 ProjectionCandidate::Object,
1346 #[tracing::instrument(
1348 skip(selcx, candidate_set, ctor, env_predicates, potentially_unnormalized_candidates)
1350 fn assemble_candidates_from_predicates<'cx, 'tcx>(
1351 selcx: &mut SelectionContext<'cx, 'tcx>,
1352 obligation: &ProjectionTyObligation<'tcx>,
1353 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1354 ctor: fn(ty::PolyProjectionPredicate<'tcx>) -> ProjectionCandidate<'tcx>,
1355 env_predicates: impl Iterator<Item = ty::Predicate<'tcx>>,
1356 potentially_unnormalized_candidates: bool,
1358 let infcx = selcx.infcx();
1359 for predicate in env_predicates {
1360 let bound_predicate = predicate.kind();
1361 if let ty::PredicateKind::Projection(data) = predicate.kind().skip_binder() {
1362 let data = bound_predicate.rebind(data);
1363 if data.projection_def_id() != obligation.predicate.item_def_id {
1367 let is_match = infcx.probe(|_| {
1368 selcx.match_projection_projections(
1371 potentially_unnormalized_candidates,
1376 ProjectionMatchesProjection::Yes => {
1377 candidate_set.push_candidate(ctor(data));
1379 if potentially_unnormalized_candidates
1380 && !obligation.predicate.has_infer_types_or_consts()
1382 // HACK: Pick the first trait def candidate for a fully
1383 // inferred predicate. This is to allow duplicates that
1384 // differ only in normalization.
1388 ProjectionMatchesProjection::Ambiguous => {
1389 candidate_set.mark_ambiguous();
1391 ProjectionMatchesProjection::No => {}
1397 #[tracing::instrument(level = "debug", skip(selcx, obligation, candidate_set))]
1398 fn assemble_candidates_from_impls<'cx, 'tcx>(
1399 selcx: &mut SelectionContext<'cx, 'tcx>,
1400 obligation: &ProjectionTyObligation<'tcx>,
1401 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1403 // If we are resolving `<T as TraitRef<...>>::Item == Type`,
1404 // start out by selecting the predicate `T as TraitRef<...>`:
1405 let poly_trait_ref = ty::Binder::dummy(obligation.predicate.trait_ref(selcx.tcx()));
1406 let trait_obligation = obligation.with(poly_trait_ref.to_poly_trait_predicate());
1407 let _ = selcx.infcx().commit_if_ok(|_| {
1408 let impl_source = match selcx.select(&trait_obligation) {
1409 Ok(Some(impl_source)) => impl_source,
1411 candidate_set.mark_ambiguous();
1415 debug!(error = ?e, "selection error");
1416 candidate_set.mark_error(e);
1421 let eligible = match &impl_source {
1422 super::ImplSource::Closure(_)
1423 | super::ImplSource::Generator(_)
1424 | super::ImplSource::FnPointer(_)
1425 | super::ImplSource::TraitAlias(_) => true,
1426 super::ImplSource::UserDefined(impl_data) => {
1427 // We have to be careful when projecting out of an
1428 // impl because of specialization. If we are not in
1429 // codegen (i.e., projection mode is not "any"), and the
1430 // impl's type is declared as default, then we disable
1431 // projection (even if the trait ref is fully
1432 // monomorphic). In the case where trait ref is not
1433 // fully monomorphic (i.e., includes type parameters),
1434 // this is because those type parameters may
1435 // ultimately be bound to types from other crates that
1436 // may have specialized impls we can't see. In the
1437 // case where the trait ref IS fully monomorphic, this
1438 // is a policy decision that we made in the RFC in
1439 // order to preserve flexibility for the crate that
1440 // defined the specializable impl to specialize later
1441 // for existing types.
1443 // In either case, we handle this by not adding a
1444 // candidate for an impl if it contains a `default`
1447 // NOTE: This should be kept in sync with the similar code in
1448 // `rustc_ty_utils::instance::resolve_associated_item()`.
1450 assoc_def(selcx, impl_data.impl_def_id, obligation.predicate.item_def_id)
1451 .map_err(|ErrorGuaranteed { .. }| ())?;
1453 if node_item.is_final() {
1454 // Non-specializable items are always projectable.
1457 // Only reveal a specializable default if we're past type-checking
1458 // and the obligation is monomorphic, otherwise passes such as
1459 // transmute checking and polymorphic MIR optimizations could
1460 // get a result which isn't correct for all monomorphizations.
1461 if obligation.param_env.reveal() == Reveal::All {
1462 // NOTE(eddyb) inference variables can resolve to parameters, so
1463 // assume `poly_trait_ref` isn't monomorphic, if it contains any.
1464 let poly_trait_ref = selcx.infcx().resolve_vars_if_possible(poly_trait_ref);
1465 !poly_trait_ref.still_further_specializable()
1468 assoc_ty = ?selcx.tcx().def_path_str(node_item.item.def_id),
1469 ?obligation.predicate,
1470 "assemble_candidates_from_impls: not eligible due to default",
1476 super::ImplSource::DiscriminantKind(..) => {
1477 // While `DiscriminantKind` is automatically implemented for every type,
1478 // the concrete discriminant may not be known yet.
1480 // Any type with multiple potential discriminant types is therefore not eligible.
1481 let self_ty = selcx.infcx().shallow_resolve(obligation.predicate.self_ty());
1483 match self_ty.kind() {
1501 | ty::GeneratorWitness(..)
1504 // Integers and floats always have `u8` as their discriminant.
1505 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(..)) => true,
1511 | ty::Placeholder(..)
1513 | ty::Error(_) => false,
1516 super::ImplSource::Pointee(..) => {
1517 // While `Pointee` is automatically implemented for every type,
1518 // the concrete metadata type may not be known yet.
1520 // Any type with multiple potential metadata types is therefore not eligible.
1521 let self_ty = selcx.infcx().shallow_resolve(obligation.predicate.self_ty());
1523 let tail = selcx.tcx().struct_tail_with_normalize(
1526 // We throw away any obligations we get from this, since we normalize
1527 // and confirm these obligations once again during confirmation
1528 normalize_with_depth(
1530 obligation.param_env,
1531 obligation.cause.clone(),
1532 obligation.recursion_depth + 1,
1556 | ty::GeneratorWitness(..)
1558 // Extern types have unit metadata, according to RFC 2850
1560 // If returned by `struct_tail_without_normalization` this is a unit struct
1561 // without any fields, or not a struct, and therefore is Sized.
1563 // If returned by `struct_tail_without_normalization` this is the empty tuple.
1565 // Integers and floats are always Sized, and so have unit type metadata.
1566 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(..)) => true,
1568 // type parameters, opaques, and unnormalized projections have pointer
1569 // metadata if they're known (e.g. by the param_env) to be sized
1570 ty::Param(_) | ty::Projection(..) | ty::Opaque(..)
1571 if selcx.infcx().predicate_must_hold_modulo_regions(
1573 ty::Binder::dummy(ty::TraitRef::new(
1574 selcx.tcx().require_lang_item(LangItem::Sized, None),
1575 selcx.tcx().mk_substs_trait(self_ty, &[]),
1578 .to_predicate(selcx.tcx()),
1585 // FIXME(compiler-errors): are Bound and Placeholder types ever known sized?
1587 | ty::Projection(..)
1590 | ty::Placeholder(..)
1593 if tail.has_infer_types() {
1594 candidate_set.mark_ambiguous();
1600 super::ImplSource::Param(..) => {
1601 // This case tell us nothing about the value of an
1602 // associated type. Consider:
1605 // trait SomeTrait { type Foo; }
1606 // fn foo<T:SomeTrait>(...) { }
1609 // If the user writes `<T as SomeTrait>::Foo`, then the `T
1610 // : SomeTrait` binding does not help us decide what the
1611 // type `Foo` is (at least, not more specifically than
1612 // what we already knew).
1614 // But wait, you say! What about an example like this:
1617 // fn bar<T:SomeTrait<Foo=usize>>(...) { ... }
1620 // Doesn't the `T : SomeTrait<Foo=usize>` predicate help
1621 // resolve `T::Foo`? And of course it does, but in fact
1622 // that single predicate is desugared into two predicates
1623 // in the compiler: a trait predicate (`T : SomeTrait`) and a
1624 // projection. And the projection where clause is handled
1625 // in `assemble_candidates_from_param_env`.
1628 super::ImplSource::Object(_) => {
1629 // Handled by the `Object` projection candidate. See
1630 // `assemble_candidates_from_object_ty` for an explanation of
1631 // why we special case object types.
1634 super::ImplSource::AutoImpl(..)
1635 | super::ImplSource::Builtin(..)
1636 | super::ImplSource::TraitUpcasting(_)
1637 | super::ImplSource::ConstDestruct(_) => {
1638 // These traits have no associated types.
1639 selcx.tcx().sess.delay_span_bug(
1640 obligation.cause.span,
1641 &format!("Cannot project an associated type from `{:?}`", impl_source),
1648 if candidate_set.push_candidate(ProjectionCandidate::Select(impl_source)) {
1659 fn confirm_candidate<'cx, 'tcx>(
1660 selcx: &mut SelectionContext<'cx, 'tcx>,
1661 obligation: &ProjectionTyObligation<'tcx>,
1662 candidate: ProjectionCandidate<'tcx>,
1663 ) -> Progress<'tcx> {
1664 debug!(?obligation, ?candidate, "confirm_candidate");
1665 let mut progress = match candidate {
1666 ProjectionCandidate::ParamEnv(poly_projection)
1667 | ProjectionCandidate::Object(poly_projection) => {
1668 confirm_param_env_candidate(selcx, obligation, poly_projection, false)
1671 ProjectionCandidate::TraitDef(poly_projection) => {
1672 confirm_param_env_candidate(selcx, obligation, poly_projection, true)
1675 ProjectionCandidate::Select(impl_source) => {
1676 confirm_select_candidate(selcx, obligation, impl_source)
1680 // When checking for cycle during evaluation, we compare predicates with
1681 // "syntactic" equality. Since normalization generally introduces a type
1682 // with new region variables, we need to resolve them to existing variables
1683 // when possible for this to work. See `auto-trait-projection-recursion.rs`
1684 // for a case where this matters.
1685 if progress.term.has_infer_regions() {
1687 progress.term.fold_with(&mut OpportunisticRegionResolver::new(selcx.infcx()));
1692 fn confirm_select_candidate<'cx, 'tcx>(
1693 selcx: &mut SelectionContext<'cx, 'tcx>,
1694 obligation: &ProjectionTyObligation<'tcx>,
1695 impl_source: Selection<'tcx>,
1696 ) -> Progress<'tcx> {
1698 super::ImplSource::UserDefined(data) => confirm_impl_candidate(selcx, obligation, data),
1699 super::ImplSource::Generator(data) => confirm_generator_candidate(selcx, obligation, data),
1700 super::ImplSource::Closure(data) => confirm_closure_candidate(selcx, obligation, data),
1701 super::ImplSource::FnPointer(data) => confirm_fn_pointer_candidate(selcx, obligation, data),
1702 super::ImplSource::DiscriminantKind(data) => {
1703 confirm_discriminant_kind_candidate(selcx, obligation, data)
1705 super::ImplSource::Pointee(data) => confirm_pointee_candidate(selcx, obligation, data),
1706 super::ImplSource::Object(_)
1707 | super::ImplSource::AutoImpl(..)
1708 | super::ImplSource::Param(..)
1709 | super::ImplSource::Builtin(..)
1710 | super::ImplSource::TraitUpcasting(_)
1711 | super::ImplSource::TraitAlias(..)
1712 | super::ImplSource::ConstDestruct(_) => {
1713 // we don't create Select candidates with this kind of resolution
1715 obligation.cause.span,
1716 "Cannot project an associated type from `{:?}`",
1723 fn confirm_generator_candidate<'cx, 'tcx>(
1724 selcx: &mut SelectionContext<'cx, 'tcx>,
1725 obligation: &ProjectionTyObligation<'tcx>,
1726 impl_source: ImplSourceGeneratorData<'tcx, PredicateObligation<'tcx>>,
1727 ) -> Progress<'tcx> {
1728 let gen_sig = impl_source.substs.as_generator().poly_sig();
1729 let Normalized { value: gen_sig, obligations } = normalize_with_depth(
1731 obligation.param_env,
1732 obligation.cause.clone(),
1733 obligation.recursion_depth + 1,
1737 debug!(?obligation, ?gen_sig, ?obligations, "confirm_generator_candidate");
1739 let tcx = selcx.tcx();
1741 let gen_def_id = tcx.require_lang_item(LangItem::Generator, None);
1743 let predicate = super::util::generator_trait_ref_and_outputs(
1746 obligation.predicate.self_ty(),
1749 .map_bound(|(trait_ref, yield_ty, return_ty)| {
1750 let name = tcx.associated_item(obligation.predicate.item_def_id).name;
1751 let ty = if name == sym::Return {
1753 } else if name == sym::Yield {
1759 ty::ProjectionPredicate {
1760 projection_ty: ty::ProjectionTy {
1761 substs: trait_ref.substs,
1762 item_def_id: obligation.predicate.item_def_id,
1768 confirm_param_env_candidate(selcx, obligation, predicate, false)
1769 .with_addl_obligations(impl_source.nested)
1770 .with_addl_obligations(obligations)
1773 fn confirm_discriminant_kind_candidate<'cx, 'tcx>(
1774 selcx: &mut SelectionContext<'cx, 'tcx>,
1775 obligation: &ProjectionTyObligation<'tcx>,
1776 _: ImplSourceDiscriminantKindData,
1777 ) -> Progress<'tcx> {
1778 let tcx = selcx.tcx();
1780 let self_ty = selcx.infcx().shallow_resolve(obligation.predicate.self_ty());
1781 // We get here from `poly_project_and_unify_type` which replaces bound vars
1782 // with placeholders
1783 debug_assert!(!self_ty.has_escaping_bound_vars());
1784 let substs = tcx.mk_substs([self_ty.into()].iter());
1786 let discriminant_def_id = tcx.require_lang_item(LangItem::Discriminant, None);
1788 let predicate = ty::ProjectionPredicate {
1789 projection_ty: ty::ProjectionTy { substs, item_def_id: discriminant_def_id },
1790 term: self_ty.discriminant_ty(tcx).into(),
1793 // We get here from `poly_project_and_unify_type` which replaces bound vars
1794 // with placeholders, so dummy is okay here.
1795 confirm_param_env_candidate(selcx, obligation, ty::Binder::dummy(predicate), false)
1798 fn confirm_pointee_candidate<'cx, 'tcx>(
1799 selcx: &mut SelectionContext<'cx, 'tcx>,
1800 obligation: &ProjectionTyObligation<'tcx>,
1801 _: ImplSourcePointeeData,
1802 ) -> Progress<'tcx> {
1803 let tcx = selcx.tcx();
1804 let self_ty = selcx.infcx().shallow_resolve(obligation.predicate.self_ty());
1806 let mut obligations = vec![];
1807 let (metadata_ty, check_is_sized) = self_ty.ptr_metadata_ty(tcx, |ty| {
1808 normalize_with_depth_to(
1810 obligation.param_env,
1811 obligation.cause.clone(),
1812 obligation.recursion_depth + 1,
1818 let sized_predicate = ty::Binder::dummy(ty::TraitRef::new(
1819 tcx.require_lang_item(LangItem::Sized, None),
1820 tcx.mk_substs_trait(self_ty, &[]),
1824 obligations.push(Obligation::new(
1825 obligation.cause.clone(),
1826 obligation.param_env,
1831 let substs = tcx.mk_substs([self_ty.into()].iter());
1832 let metadata_def_id = tcx.require_lang_item(LangItem::Metadata, None);
1834 let predicate = ty::ProjectionPredicate {
1835 projection_ty: ty::ProjectionTy { substs, item_def_id: metadata_def_id },
1836 term: metadata_ty.into(),
1839 confirm_param_env_candidate(selcx, obligation, ty::Binder::dummy(predicate), false)
1840 .with_addl_obligations(obligations)
1843 fn confirm_fn_pointer_candidate<'cx, 'tcx>(
1844 selcx: &mut SelectionContext<'cx, 'tcx>,
1845 obligation: &ProjectionTyObligation<'tcx>,
1846 fn_pointer_impl_source: ImplSourceFnPointerData<'tcx, PredicateObligation<'tcx>>,
1847 ) -> Progress<'tcx> {
1848 let fn_type = selcx.infcx().shallow_resolve(fn_pointer_impl_source.fn_ty);
1849 let sig = fn_type.fn_sig(selcx.tcx());
1850 let Normalized { value: sig, obligations } = normalize_with_depth(
1852 obligation.param_env,
1853 obligation.cause.clone(),
1854 obligation.recursion_depth + 1,
1858 confirm_callable_candidate(selcx, obligation, sig, util::TupleArgumentsFlag::Yes)
1859 .with_addl_obligations(fn_pointer_impl_source.nested)
1860 .with_addl_obligations(obligations)
1863 fn confirm_closure_candidate<'cx, 'tcx>(
1864 selcx: &mut SelectionContext<'cx, 'tcx>,
1865 obligation: &ProjectionTyObligation<'tcx>,
1866 impl_source: ImplSourceClosureData<'tcx, PredicateObligation<'tcx>>,
1867 ) -> Progress<'tcx> {
1868 let closure_sig = impl_source.substs.as_closure().sig();
1869 let Normalized { value: closure_sig, obligations } = normalize_with_depth(
1871 obligation.param_env,
1872 obligation.cause.clone(),
1873 obligation.recursion_depth + 1,
1877 debug!(?obligation, ?closure_sig, ?obligations, "confirm_closure_candidate");
1879 confirm_callable_candidate(selcx, obligation, closure_sig, util::TupleArgumentsFlag::No)
1880 .with_addl_obligations(impl_source.nested)
1881 .with_addl_obligations(obligations)
1884 fn confirm_callable_candidate<'cx, 'tcx>(
1885 selcx: &mut SelectionContext<'cx, 'tcx>,
1886 obligation: &ProjectionTyObligation<'tcx>,
1887 fn_sig: ty::PolyFnSig<'tcx>,
1888 flag: util::TupleArgumentsFlag,
1889 ) -> Progress<'tcx> {
1890 let tcx = selcx.tcx();
1892 debug!(?obligation, ?fn_sig, "confirm_callable_candidate");
1894 let fn_once_def_id = tcx.require_lang_item(LangItem::FnOnce, None);
1895 let fn_once_output_def_id = tcx.require_lang_item(LangItem::FnOnceOutput, None);
1897 let predicate = super::util::closure_trait_ref_and_return_type(
1900 obligation.predicate.self_ty(),
1904 .map_bound(|(trait_ref, ret_type)| ty::ProjectionPredicate {
1905 projection_ty: ty::ProjectionTy {
1906 substs: trait_ref.substs,
1907 item_def_id: fn_once_output_def_id,
1909 term: ret_type.into(),
1912 confirm_param_env_candidate(selcx, obligation, predicate, true)
1915 fn confirm_param_env_candidate<'cx, 'tcx>(
1916 selcx: &mut SelectionContext<'cx, 'tcx>,
1917 obligation: &ProjectionTyObligation<'tcx>,
1918 poly_cache_entry: ty::PolyProjectionPredicate<'tcx>,
1919 potentially_unnormalized_candidate: bool,
1920 ) -> Progress<'tcx> {
1921 let infcx = selcx.infcx();
1922 let cause = &obligation.cause;
1923 let param_env = obligation.param_env;
1925 let cache_entry = infcx.replace_bound_vars_with_fresh_vars(
1927 LateBoundRegionConversionTime::HigherRankedType,
1931 let cache_projection = cache_entry.projection_ty;
1932 let mut nested_obligations = Vec::new();
1933 let obligation_projection = obligation.predicate;
1934 let obligation_projection = ensure_sufficient_stack(|| {
1935 normalize_with_depth_to(
1937 obligation.param_env,
1938 obligation.cause.clone(),
1939 obligation.recursion_depth + 1,
1940 obligation_projection,
1941 &mut nested_obligations,
1944 let cache_projection = if potentially_unnormalized_candidate {
1945 ensure_sufficient_stack(|| {
1946 normalize_with_depth_to(
1948 obligation.param_env,
1949 obligation.cause.clone(),
1950 obligation.recursion_depth + 1,
1952 &mut nested_obligations,
1959 debug!(?cache_projection, ?obligation_projection);
1961 match infcx.at(cause, param_env).eq(cache_projection, obligation_projection) {
1962 Ok(InferOk { value: _, obligations }) => {
1963 nested_obligations.extend(obligations);
1964 assoc_ty_own_obligations(selcx, obligation, &mut nested_obligations);
1965 // FIXME(associated_const_equality): Handle consts here as well? Maybe this progress type should just take
1967 Progress { term: cache_entry.term, obligations: nested_obligations }
1971 "Failed to unify obligation `{:?}` with poly_projection `{:?}`: {:?}",
1972 obligation, poly_cache_entry, e,
1974 debug!("confirm_param_env_candidate: {}", msg);
1975 let err = infcx.tcx.ty_error_with_message(obligation.cause.span, &msg);
1976 Progress { term: err.into(), obligations: vec![] }
1981 fn confirm_impl_candidate<'cx, 'tcx>(
1982 selcx: &mut SelectionContext<'cx, 'tcx>,
1983 obligation: &ProjectionTyObligation<'tcx>,
1984 impl_impl_source: ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>>,
1985 ) -> Progress<'tcx> {
1986 let tcx = selcx.tcx();
1988 let ImplSourceUserDefinedData { impl_def_id, substs, mut nested } = impl_impl_source;
1989 let assoc_item_id = obligation.predicate.item_def_id;
1990 let trait_def_id = tcx.trait_id_of_impl(impl_def_id).unwrap();
1992 let param_env = obligation.param_env;
1993 let Ok(assoc_ty) = assoc_def(selcx, impl_def_id, assoc_item_id) else {
1994 return Progress { term: tcx.ty_error().into(), obligations: nested };
1997 if !assoc_ty.item.defaultness(tcx).has_value() {
1998 // This means that the impl is missing a definition for the
1999 // associated type. This error will be reported by the type
2000 // checker method `check_impl_items_against_trait`, so here we
2001 // just return Error.
2003 "confirm_impl_candidate: no associated type {:?} for {:?}",
2004 assoc_ty.item.name, obligation.predicate
2006 return Progress { term: tcx.ty_error().into(), obligations: nested };
2008 // If we're trying to normalize `<Vec<u32> as X>::A<S>` using
2009 //`impl<T> X for Vec<T> { type A<Y> = Box<Y>; }`, then:
2011 // * `obligation.predicate.substs` is `[Vec<u32>, S]`
2012 // * `substs` is `[u32]`
2013 // * `substs` ends up as `[u32, S]`
2014 let substs = obligation.predicate.substs.rebase_onto(tcx, trait_def_id, substs);
2016 translate_substs(selcx.infcx(), param_env, impl_def_id, substs, assoc_ty.defining_node);
2017 let ty = tcx.bound_type_of(assoc_ty.item.def_id);
2018 let is_const = matches!(tcx.def_kind(assoc_ty.item.def_id), DefKind::AssocConst);
2019 let term: ty::EarlyBinder<ty::Term<'tcx>> = if is_const {
2020 let identity_substs =
2021 crate::traits::InternalSubsts::identity_for_item(tcx, assoc_ty.item.def_id);
2022 let did = ty::WithOptConstParam::unknown(assoc_ty.item.def_id);
2023 let kind = ty::ConstKind::Unevaluated(ty::Unevaluated::new(did, identity_substs));
2024 ty.map_bound(|ty| tcx.mk_const(ty::ConstS { ty, kind }).into())
2026 ty.map_bound(|ty| ty.into())
2028 if substs.len() != tcx.generics_of(assoc_ty.item.def_id).count() {
2029 let err = tcx.ty_error_with_message(
2030 obligation.cause.span,
2031 "impl item and trait item have different parameter counts",
2033 Progress { term: err.into(), obligations: nested }
2035 assoc_ty_own_obligations(selcx, obligation, &mut nested);
2036 Progress { term: term.subst(tcx, substs), obligations: nested }
2040 // Get obligations corresponding to the predicates from the where-clause of the
2041 // associated type itself.
2042 // Note: `feature(generic_associated_types)` is required to write such
2043 // predicates, even for non-generic associated types.
2044 fn assoc_ty_own_obligations<'cx, 'tcx>(
2045 selcx: &mut SelectionContext<'cx, 'tcx>,
2046 obligation: &ProjectionTyObligation<'tcx>,
2047 nested: &mut Vec<PredicateObligation<'tcx>>,
2049 let tcx = selcx.tcx();
2050 for predicate in tcx
2051 .predicates_of(obligation.predicate.item_def_id)
2052 .instantiate_own(tcx, obligation.predicate.substs)
2055 let normalized = normalize_with_depth_to(
2057 obligation.param_env,
2058 obligation.cause.clone(),
2059 obligation.recursion_depth + 1,
2063 nested.push(Obligation::with_depth(
2064 obligation.cause.clone(),
2065 obligation.recursion_depth + 1,
2066 obligation.param_env,
2072 /// Locate the definition of an associated type in the specialization hierarchy,
2073 /// starting from the given impl.
2075 /// Based on the "projection mode", this lookup may in fact only examine the
2076 /// topmost impl. See the comments for `Reveal` for more details.
2078 selcx: &SelectionContext<'_, '_>,
2080 assoc_def_id: DefId,
2081 ) -> Result<specialization_graph::LeafDef, ErrorGuaranteed> {
2082 let tcx = selcx.tcx();
2083 let trait_def_id = tcx.impl_trait_ref(impl_def_id).unwrap().def_id;
2084 let trait_def = tcx.trait_def(trait_def_id);
2086 // This function may be called while we are still building the
2087 // specialization graph that is queried below (via TraitDef::ancestors()),
2088 // so, in order to avoid unnecessary infinite recursion, we manually look
2089 // for the associated item at the given impl.
2090 // If there is no such item in that impl, this function will fail with a
2091 // cycle error if the specialization graph is currently being built.
2092 if let Some(&impl_item_id) = tcx.impl_item_implementor_ids(impl_def_id).get(&assoc_def_id) {
2093 let item = tcx.associated_item(impl_item_id);
2094 let impl_node = specialization_graph::Node::Impl(impl_def_id);
2095 return Ok(specialization_graph::LeafDef {
2097 defining_node: impl_node,
2098 finalizing_node: if item.defaultness(tcx).is_default() {
2106 let ancestors = trait_def.ancestors(tcx, impl_def_id)?;
2107 if let Some(assoc_item) = ancestors.leaf_def(tcx, assoc_def_id) {
2110 // This is saying that neither the trait nor
2111 // the impl contain a definition for this
2112 // associated type. Normally this situation
2113 // could only arise through a compiler bug --
2114 // if the user wrote a bad item name, it
2115 // should have failed in astconv.
2117 "No associated type `{}` for {}",
2118 tcx.item_name(assoc_def_id),
2119 tcx.def_path_str(impl_def_id)
2124 pub(crate) trait ProjectionCacheKeyExt<'cx, 'tcx>: Sized {
2125 fn from_poly_projection_predicate(
2126 selcx: &mut SelectionContext<'cx, 'tcx>,
2127 predicate: ty::PolyProjectionPredicate<'tcx>,
2131 impl<'cx, 'tcx> ProjectionCacheKeyExt<'cx, 'tcx> for ProjectionCacheKey<'tcx> {
2132 fn from_poly_projection_predicate(
2133 selcx: &mut SelectionContext<'cx, 'tcx>,
2134 predicate: ty::PolyProjectionPredicate<'tcx>,
2136 let infcx = selcx.infcx();
2137 // We don't do cross-snapshot caching of obligations with escaping regions,
2138 // so there's no cache key to use
2139 predicate.no_bound_vars().map(|predicate| {
2140 ProjectionCacheKey::new(
2141 // We don't attempt to match up with a specific type-variable state
2142 // from a specific call to `opt_normalize_projection_type` - if
2143 // there's no precise match, the original cache entry is "stranded"
2145 infcx.resolve_vars_if_possible(predicate.projection_ty),