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");
255 let actual = obligation.predicate.term;
256 // For an example where this is neccessary see src/test/ui/impl-trait/nested-return-type2.rs
257 // This allows users to omit re-mentioning all bounds on an associated type and just use an
258 // `impl Trait` for the assoc type to add more bounds.
259 let InferOk { value: actual, obligations: new } =
260 selcx.infcx().replace_opaque_types_with_inference_vars(
262 obligation.cause.body_id,
263 obligation.cause.span,
264 obligation.param_env,
266 obligations.extend(new);
268 match infcx.at(&obligation.cause, obligation.param_env).eq(normalized, actual) {
269 Ok(InferOk { obligations: inferred_obligations, value: () }) => {
270 obligations.extend(inferred_obligations);
271 ProjectAndUnifyResult::Holds(obligations)
274 debug!("equating types encountered error {:?}", err);
275 ProjectAndUnifyResult::MismatchedProjectionTypes(MismatchedProjectionTypes { err })
280 /// Normalizes any associated type projections in `value`, replacing
281 /// them with a fully resolved type where possible. The return value
282 /// combines the normalized result and any additional obligations that
283 /// were incurred as result.
284 pub fn normalize<'a, 'b, 'tcx, T>(
285 selcx: &'a mut SelectionContext<'b, 'tcx>,
286 param_env: ty::ParamEnv<'tcx>,
287 cause: ObligationCause<'tcx>,
289 ) -> Normalized<'tcx, T>
291 T: TypeFoldable<'tcx>,
293 let mut obligations = Vec::new();
294 let value = normalize_to(selcx, param_env, cause, value, &mut obligations);
295 Normalized { value, obligations }
298 pub fn normalize_to<'a, 'b, 'tcx, T>(
299 selcx: &'a mut SelectionContext<'b, 'tcx>,
300 param_env: ty::ParamEnv<'tcx>,
301 cause: ObligationCause<'tcx>,
303 obligations: &mut Vec<PredicateObligation<'tcx>>,
306 T: TypeFoldable<'tcx>,
308 normalize_with_depth_to(selcx, param_env, cause, 0, value, obligations)
311 /// As `normalize`, but with a custom depth.
312 pub fn normalize_with_depth<'a, 'b, 'tcx, T>(
313 selcx: &'a mut SelectionContext<'b, 'tcx>,
314 param_env: ty::ParamEnv<'tcx>,
315 cause: ObligationCause<'tcx>,
318 ) -> Normalized<'tcx, T>
320 T: TypeFoldable<'tcx>,
322 let mut obligations = Vec::new();
323 let value = normalize_with_depth_to(selcx, param_env, cause, depth, value, &mut obligations);
324 Normalized { value, obligations }
327 #[instrument(level = "info", skip(selcx, param_env, cause, obligations))]
328 pub fn normalize_with_depth_to<'a, 'b, 'tcx, T>(
329 selcx: &'a mut SelectionContext<'b, 'tcx>,
330 param_env: ty::ParamEnv<'tcx>,
331 cause: ObligationCause<'tcx>,
334 obligations: &mut Vec<PredicateObligation<'tcx>>,
337 T: TypeFoldable<'tcx>,
339 debug!(obligations.len = obligations.len());
340 let mut normalizer = AssocTypeNormalizer::new(selcx, param_env, cause, depth, obligations);
341 let result = ensure_sufficient_stack(|| normalizer.fold(value));
342 debug!(?result, obligations.len = normalizer.obligations.len());
343 debug!(?normalizer.obligations,);
347 #[instrument(level = "info", skip(selcx, param_env, cause, obligations))]
348 pub fn try_normalize_with_depth_to<'a, 'b, 'tcx, T>(
349 selcx: &'a mut SelectionContext<'b, 'tcx>,
350 param_env: ty::ParamEnv<'tcx>,
351 cause: ObligationCause<'tcx>,
354 obligations: &mut Vec<PredicateObligation<'tcx>>,
357 T: TypeFoldable<'tcx>,
359 debug!(obligations.len = obligations.len());
360 let mut normalizer = AssocTypeNormalizer::new_without_eager_inference_replacement(
367 let result = ensure_sufficient_stack(|| normalizer.fold(value));
368 debug!(?result, obligations.len = normalizer.obligations.len());
369 debug!(?normalizer.obligations,);
373 pub(crate) fn needs_normalization<'tcx, T: TypeVisitable<'tcx>>(value: &T, reveal: Reveal) -> bool {
375 Reveal::UserFacing => value
376 .has_type_flags(ty::TypeFlags::HAS_TY_PROJECTION | ty::TypeFlags::HAS_CT_PROJECTION),
377 Reveal::All => value.has_type_flags(
378 ty::TypeFlags::HAS_TY_PROJECTION
379 | ty::TypeFlags::HAS_TY_OPAQUE
380 | ty::TypeFlags::HAS_CT_PROJECTION,
385 struct AssocTypeNormalizer<'a, 'b, 'tcx> {
386 selcx: &'a mut SelectionContext<'b, 'tcx>,
387 param_env: ty::ParamEnv<'tcx>,
388 cause: ObligationCause<'tcx>,
389 obligations: &'a mut Vec<PredicateObligation<'tcx>>,
391 universes: Vec<Option<ty::UniverseIndex>>,
392 /// If true, when a projection is unable to be completed, an inference
393 /// variable will be created and an obligation registered to project to that
394 /// inference variable. Also, constants will be eagerly evaluated.
395 eager_inference_replacement: bool,
398 impl<'a, 'b, 'tcx> AssocTypeNormalizer<'a, 'b, 'tcx> {
400 selcx: &'a mut SelectionContext<'b, 'tcx>,
401 param_env: ty::ParamEnv<'tcx>,
402 cause: ObligationCause<'tcx>,
404 obligations: &'a mut Vec<PredicateObligation<'tcx>>,
405 ) -> AssocTypeNormalizer<'a, 'b, 'tcx> {
406 AssocTypeNormalizer {
413 eager_inference_replacement: true,
417 fn new_without_eager_inference_replacement(
418 selcx: &'a mut SelectionContext<'b, 'tcx>,
419 param_env: ty::ParamEnv<'tcx>,
420 cause: ObligationCause<'tcx>,
422 obligations: &'a mut Vec<PredicateObligation<'tcx>>,
423 ) -> AssocTypeNormalizer<'a, 'b, 'tcx> {
424 AssocTypeNormalizer {
431 eager_inference_replacement: false,
435 fn fold<T: TypeFoldable<'tcx>>(&mut self, value: T) -> T {
436 let value = self.selcx.infcx().resolve_vars_if_possible(value);
440 !value.has_escaping_bound_vars(),
441 "Normalizing {:?} without wrapping in a `Binder`",
445 if !needs_normalization(&value, self.param_env.reveal()) {
448 value.fold_with(self)
453 impl<'a, 'b, 'tcx> TypeFolder<'tcx> for AssocTypeNormalizer<'a, 'b, 'tcx> {
454 fn tcx<'c>(&'c self) -> TyCtxt<'tcx> {
458 fn fold_binder<T: TypeFoldable<'tcx>>(
460 t: ty::Binder<'tcx, T>,
461 ) -> ty::Binder<'tcx, T> {
462 self.universes.push(None);
463 let t = t.super_fold_with(self);
464 self.universes.pop();
468 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
469 if !needs_normalization(&ty, self.param_env.reveal()) {
473 // We try to be a little clever here as a performance optimization in
474 // cases where there are nested projections under binders.
477 // for<'a> fn(<T as Foo>::One<'a, Box<dyn Bar<'a, Item=<T as Foo>::Two<'a>>>>)
479 // We normalize the substs on the projection before the projecting, but
480 // if we're naive, we'll
481 // replace bound vars on inner, project inner, replace placeholders on inner,
482 // replace bound vars on outer, project outer, replace placeholders on outer
484 // However, if we're a bit more clever, we can replace the bound vars
485 // on the entire type before normalizing nested projections, meaning we
486 // replace bound vars on outer, project inner,
487 // project outer, replace placeholders on outer
489 // This is possible because the inner `'a` will already be a placeholder
490 // when we need to normalize the inner projection
492 // On the other hand, this does add a bit of complexity, since we only
493 // replace bound vars if the current type is a `Projection` and we need
494 // to make sure we don't forget to fold the substs regardless.
497 // This is really important. While we *can* handle this, this has
498 // severe performance implications for large opaque types with
499 // late-bound regions. See `issue-88862` benchmark.
500 ty::Opaque(def_id, substs) if !substs.has_escaping_bound_vars() => {
501 // Only normalize `impl Trait` outside of type inference, usually in codegen.
502 match self.param_env.reveal() {
503 Reveal::UserFacing => ty.super_fold_with(self),
506 let recursion_limit = self.tcx().recursion_limit();
507 if !recursion_limit.value_within_limit(self.depth) {
508 let obligation = Obligation::with_depth(
514 self.selcx.infcx().report_overflow_error(&obligation, true);
517 let substs = substs.fold_with(self);
518 let generic_ty = self.tcx().bound_type_of(def_id);
519 let concrete_ty = generic_ty.subst(self.tcx(), substs);
521 let folded_ty = self.fold_ty(concrete_ty);
528 ty::Projection(data) if !data.has_escaping_bound_vars() => {
529 // This branch is *mostly* just an optimization: when we don't
530 // have escaping bound vars, we don't need to replace them with
531 // placeholders (see branch below). *Also*, we know that we can
532 // register an obligation to *later* project, since we know
533 // there won't be bound vars there.
534 let data = data.fold_with(self);
535 let normalized_ty = if self.eager_inference_replacement {
536 normalize_projection_type(
542 &mut self.obligations,
545 opt_normalize_projection_type(
551 &mut self.obligations,
555 .unwrap_or_else(|| ty::Term::Ty(ty.super_fold_with(self)))
561 obligations.len = ?self.obligations.len(),
562 "AssocTypeNormalizer: normalized type"
564 normalized_ty.ty().unwrap()
567 ty::Projection(data) => {
568 // If there are escaping bound vars, we temporarily replace the
569 // bound vars with placeholders. Note though, that in the case
570 // that we still can't project for whatever reason (e.g. self
571 // type isn't known enough), we *can't* register an obligation
572 // and return an inference variable (since then that obligation
573 // would have bound vars and that's a can of worms). Instead,
574 // we just give up and fall back to pretending like we never tried!
576 // Note: this isn't necessarily the final approach here; we may
577 // want to figure out how to register obligations with escaping vars
578 // or handle this some other way.
580 let infcx = self.selcx.infcx();
581 let (data, mapped_regions, mapped_types, mapped_consts) =
582 BoundVarReplacer::replace_bound_vars(infcx, &mut self.universes, data);
583 let data = data.fold_with(self);
584 let normalized_ty = opt_normalize_projection_type(
590 &mut self.obligations,
594 .map(|term| term.ty().unwrap())
595 .map(|normalized_ty| {
596 PlaceholderReplacer::replace_placeholders(
605 .unwrap_or_else(|| ty.super_fold_with(self));
611 obligations.len = ?self.obligations.len(),
612 "AssocTypeNormalizer: normalized type"
617 _ => ty.super_fold_with(self),
621 #[instrument(skip(self), level = "debug")]
622 fn fold_const(&mut self, constant: ty::Const<'tcx>) -> ty::Const<'tcx> {
623 if self.selcx.tcx().lazy_normalization() || !self.eager_inference_replacement {
626 let constant = constant.super_fold_with(self);
628 debug!("self.param_env: {:?}", self.param_env);
629 constant.eval(self.selcx.tcx(), self.param_env)
634 fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
635 if p.allow_normalization() && needs_normalization(&p, self.param_env.reveal()) {
636 p.super_fold_with(self)
643 pub struct BoundVarReplacer<'me, 'tcx> {
644 infcx: &'me InferCtxt<'me, 'tcx>,
645 // These three maps track the bound variable that were replaced by placeholders. It might be
646 // nice to remove these since we already have the `kind` in the placeholder; we really just need
647 // the `var` (but we *could* bring that into scope if we were to track them as we pass them).
648 mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
649 mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy>,
650 mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
651 // The current depth relative to *this* folding, *not* the entire normalization. In other words,
652 // the depth of binders we've passed here.
653 current_index: ty::DebruijnIndex,
654 // The `UniverseIndex` of the binding levels above us. These are optional, since we are lazy:
655 // we don't actually create a universe until we see a bound var we have to replace.
656 universe_indices: &'me mut Vec<Option<ty::UniverseIndex>>,
659 impl<'me, 'tcx> BoundVarReplacer<'me, 'tcx> {
660 /// Returns `Some` if we *were* able to replace bound vars. If there are any bound vars that
661 /// use a binding level above `universe_indices.len()`, we fail.
662 pub fn replace_bound_vars<T: TypeFoldable<'tcx>>(
663 infcx: &'me InferCtxt<'me, 'tcx>,
664 universe_indices: &'me mut Vec<Option<ty::UniverseIndex>>,
668 BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
669 BTreeMap<ty::PlaceholderType, ty::BoundTy>,
670 BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
672 let mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion> = BTreeMap::new();
673 let mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy> = BTreeMap::new();
674 let mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar> = BTreeMap::new();
676 let mut replacer = BoundVarReplacer {
681 current_index: ty::INNERMOST,
685 let value = value.fold_with(&mut replacer);
687 (value, replacer.mapped_regions, replacer.mapped_types, replacer.mapped_consts)
690 fn universe_for(&mut self, debruijn: ty::DebruijnIndex) -> ty::UniverseIndex {
691 let infcx = self.infcx;
693 self.universe_indices.len() + self.current_index.as_usize() - debruijn.as_usize() - 1;
694 let universe = self.universe_indices[index].unwrap_or_else(|| {
695 for i in self.universe_indices.iter_mut().take(index + 1) {
696 *i = i.or_else(|| Some(infcx.create_next_universe()))
698 self.universe_indices[index].unwrap()
704 impl<'tcx> TypeFolder<'tcx> for BoundVarReplacer<'_, 'tcx> {
705 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
709 fn fold_binder<T: TypeFoldable<'tcx>>(
711 t: ty::Binder<'tcx, T>,
712 ) -> ty::Binder<'tcx, T> {
713 self.current_index.shift_in(1);
714 let t = t.super_fold_with(self);
715 self.current_index.shift_out(1);
719 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
721 ty::ReLateBound(debruijn, _)
722 if debruijn.as_usize() + 1
723 > self.current_index.as_usize() + self.universe_indices.len() =>
725 bug!("Bound vars outside of `self.universe_indices`");
727 ty::ReLateBound(debruijn, br) if debruijn >= self.current_index => {
728 let universe = self.universe_for(debruijn);
729 let p = ty::PlaceholderRegion { universe, name: br.kind };
730 self.mapped_regions.insert(p, br);
731 self.infcx.tcx.mk_region(ty::RePlaceholder(p))
737 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
739 ty::Bound(debruijn, _)
740 if debruijn.as_usize() + 1
741 > self.current_index.as_usize() + self.universe_indices.len() =>
743 bug!("Bound vars outside of `self.universe_indices`");
745 ty::Bound(debruijn, bound_ty) if debruijn >= self.current_index => {
746 let universe = self.universe_for(debruijn);
747 let p = ty::PlaceholderType { universe, name: bound_ty.var };
748 self.mapped_types.insert(p, bound_ty);
749 self.infcx.tcx.mk_ty(ty::Placeholder(p))
751 _ if t.has_vars_bound_at_or_above(self.current_index) => t.super_fold_with(self),
756 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
758 ty::ConstKind::Bound(debruijn, _)
759 if debruijn.as_usize() + 1
760 > self.current_index.as_usize() + self.universe_indices.len() =>
762 bug!("Bound vars outside of `self.universe_indices`");
764 ty::ConstKind::Bound(debruijn, bound_const) if debruijn >= self.current_index => {
765 let universe = self.universe_for(debruijn);
766 let p = ty::PlaceholderConst { universe, name: bound_const };
767 self.mapped_consts.insert(p, bound_const);
770 .mk_const(ty::ConstS { kind: ty::ConstKind::Placeholder(p), ty: ct.ty() })
772 _ => ct.super_fold_with(self),
776 fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
777 if p.has_vars_bound_at_or_above(self.current_index) { p.super_fold_with(self) } else { p }
781 // The inverse of `BoundVarReplacer`: replaces placeholders with the bound vars from which they came.
782 pub struct PlaceholderReplacer<'me, '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>],
788 current_index: ty::DebruijnIndex,
791 impl<'me, 'tcx> PlaceholderReplacer<'me, 'tcx> {
792 pub fn replace_placeholders<T: TypeFoldable<'tcx>>(
793 infcx: &'me InferCtxt<'me, 'tcx>,
794 mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
795 mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy>,
796 mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
797 universe_indices: &'me [Option<ty::UniverseIndex>],
800 let mut replacer = PlaceholderReplacer {
806 current_index: ty::INNERMOST,
808 value.fold_with(&mut replacer)
812 impl<'tcx> TypeFolder<'tcx> for PlaceholderReplacer<'_, 'tcx> {
813 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
817 fn fold_binder<T: TypeFoldable<'tcx>>(
819 t: ty::Binder<'tcx, T>,
820 ) -> ty::Binder<'tcx, T> {
821 if !t.has_placeholders() && !t.has_infer_regions() {
824 self.current_index.shift_in(1);
825 let t = t.super_fold_with(self);
826 self.current_index.shift_out(1);
830 fn fold_region(&mut self, r0: ty::Region<'tcx>) -> ty::Region<'tcx> {
836 .unwrap_region_constraints()
837 .opportunistic_resolve_region(self.infcx.tcx, r0),
842 ty::RePlaceholder(p) => {
843 let replace_var = self.mapped_regions.get(&p);
845 Some(replace_var) => {
849 .position(|u| matches!(u, Some(pu) if *pu == p.universe))
850 .unwrap_or_else(|| bug!("Unexpected placeholder universe."));
851 let db = ty::DebruijnIndex::from_usize(
852 self.universe_indices.len() - index + self.current_index.as_usize() - 1,
854 self.tcx().mk_region(ty::ReLateBound(db, *replace_var))
862 debug!(?r0, ?r1, ?r2, "fold_region");
867 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
869 ty::Placeholder(p) => {
870 let replace_var = self.mapped_types.get(&p);
872 Some(replace_var) => {
876 .position(|u| matches!(u, Some(pu) if *pu == p.universe))
877 .unwrap_or_else(|| bug!("Unexpected placeholder universe."));
878 let db = ty::DebruijnIndex::from_usize(
879 self.universe_indices.len() - index + self.current_index.as_usize() - 1,
881 self.tcx().mk_ty(ty::Bound(db, *replace_var))
887 _ if ty.has_placeholders() || ty.has_infer_regions() => ty.super_fold_with(self),
892 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
893 if let ty::ConstKind::Placeholder(p) = ct.kind() {
894 let replace_var = self.mapped_consts.get(&p);
896 Some(replace_var) => {
900 .position(|u| matches!(u, Some(pu) if *pu == p.universe))
901 .unwrap_or_else(|| bug!("Unexpected placeholder universe."));
902 let db = ty::DebruijnIndex::from_usize(
903 self.universe_indices.len() - index + self.current_index.as_usize() - 1,
905 self.tcx().mk_const(ty::ConstS {
906 kind: ty::ConstKind::Bound(db, *replace_var),
913 ct.super_fold_with(self)
918 /// The guts of `normalize`: normalize a specific projection like `<T
919 /// as Trait>::Item`. The result is always a type (and possibly
920 /// additional obligations). If ambiguity arises, which implies that
921 /// there are unresolved type variables in the projection, we will
922 /// substitute a fresh type variable `$X` and generate a new
923 /// obligation `<T as Trait>::Item == $X` for later.
924 pub fn normalize_projection_type<'a, 'b, 'tcx>(
925 selcx: &'a mut SelectionContext<'b, 'tcx>,
926 param_env: ty::ParamEnv<'tcx>,
927 projection_ty: ty::ProjectionTy<'tcx>,
928 cause: ObligationCause<'tcx>,
930 obligations: &mut Vec<PredicateObligation<'tcx>>,
932 opt_normalize_projection_type(
942 .unwrap_or_else(move || {
943 // if we bottom out in ambiguity, create a type variable
944 // and a deferred predicate to resolve this when more type
945 // information is available.
949 .infer_projection(param_env, projection_ty, cause, depth + 1, obligations)
954 /// The guts of `normalize`: normalize a specific projection like `<T
955 /// as Trait>::Item`. The result is always a type (and possibly
956 /// additional obligations). Returns `None` in the case of ambiguity,
957 /// which indicates that there are unbound type variables.
959 /// This function used to return `Option<NormalizedTy<'tcx>>`, which contains a
960 /// `Ty<'tcx>` and an obligations vector. But that obligation vector was very
961 /// often immediately appended to another obligations vector. So now this
962 /// function takes an obligations vector and appends to it directly, which is
963 /// slightly uglier but avoids the need for an extra short-lived allocation.
964 #[instrument(level = "debug", skip(selcx, param_env, cause, obligations))]
965 fn opt_normalize_projection_type<'a, 'b, 'tcx>(
966 selcx: &'a mut SelectionContext<'b, 'tcx>,
967 param_env: ty::ParamEnv<'tcx>,
968 projection_ty: ty::ProjectionTy<'tcx>,
969 cause: ObligationCause<'tcx>,
971 obligations: &mut Vec<PredicateObligation<'tcx>>,
972 ) -> Result<Option<Term<'tcx>>, InProgress> {
973 let infcx = selcx.infcx();
974 // Don't use the projection cache in intercrate mode -
975 // the `infcx` may be re-used between intercrate in non-intercrate
976 // mode, which could lead to using incorrect cache results.
977 let use_cache = !selcx.is_intercrate();
979 let projection_ty = infcx.resolve_vars_if_possible(projection_ty);
980 let cache_key = ProjectionCacheKey::new(projection_ty);
982 // FIXME(#20304) For now, I am caching here, which is good, but it
983 // means we don't capture the type variables that are created in
984 // the case of ambiguity. Which means we may create a large stream
985 // of such variables. OTOH, if we move the caching up a level, we
986 // would not benefit from caching when proving `T: Trait<U=Foo>`
987 // bounds. It might be the case that we want two distinct caches,
988 // or else another kind of cache entry.
990 let cache_result = if use_cache {
991 infcx.inner.borrow_mut().projection_cache().try_start(cache_key)
996 Ok(()) => debug!("no cache"),
997 Err(ProjectionCacheEntry::Ambiguous) => {
998 // If we found ambiguity the last time, that means we will continue
999 // to do so until some type in the key changes (and we know it
1000 // hasn't, because we just fully resolved it).
1001 debug!("found cache entry: ambiguous");
1004 Err(ProjectionCacheEntry::InProgress) => {
1005 // Under lazy normalization, this can arise when
1006 // bootstrapping. That is, imagine an environment with a
1007 // where-clause like `A::B == u32`. Now, if we are asked
1008 // to normalize `A::B`, we will want to check the
1009 // where-clauses in scope. So we will try to unify `A::B`
1010 // with `A::B`, which can trigger a recursive
1013 debug!("found cache entry: in-progress");
1015 // Cache that normalizing this projection resulted in a cycle. This
1016 // should ensure that, unless this happens within a snapshot that's
1017 // rolled back, fulfillment or evaluation will notice the cycle.
1020 infcx.inner.borrow_mut().projection_cache().recur(cache_key);
1022 return Err(InProgress);
1024 Err(ProjectionCacheEntry::Recur) => {
1025 debug!("recur cache");
1026 return Err(InProgress);
1028 Err(ProjectionCacheEntry::NormalizedTy { ty, complete: _ }) => {
1029 // This is the hottest path in this function.
1031 // If we find the value in the cache, then return it along
1032 // with the obligations that went along with it. Note
1033 // that, when using a fulfillment context, these
1034 // obligations could in principle be ignored: they have
1035 // already been registered when the cache entry was
1036 // created (and hence the new ones will quickly be
1037 // discarded as duplicated). But when doing trait
1038 // evaluation this is not the case, and dropping the trait
1039 // evaluations can causes ICEs (e.g., #43132).
1040 debug!(?ty, "found normalized ty");
1041 obligations.extend(ty.obligations);
1042 return Ok(Some(ty.value));
1044 Err(ProjectionCacheEntry::Error) => {
1045 debug!("opt_normalize_projection_type: found error");
1046 let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth);
1047 obligations.extend(result.obligations);
1048 return Ok(Some(result.value.into()));
1052 let obligation = Obligation::with_depth(cause.clone(), depth, param_env, projection_ty);
1054 match project(selcx, &obligation) {
1055 Ok(Projected::Progress(Progress {
1056 term: projected_term,
1057 obligations: mut projected_obligations,
1059 // if projection succeeded, then what we get out of this
1060 // is also non-normalized (consider: it was derived from
1061 // an impl, where-clause etc) and hence we must
1064 let projected_term = selcx.infcx().resolve_vars_if_possible(projected_term);
1066 let mut result = if projected_term.has_projections() {
1067 let mut normalizer = AssocTypeNormalizer::new(
1072 &mut projected_obligations,
1074 let normalized_ty = normalizer.fold(projected_term);
1076 Normalized { value: normalized_ty, obligations: projected_obligations }
1078 Normalized { value: projected_term, obligations: projected_obligations }
1081 let mut deduped: SsoHashSet<_> = Default::default();
1082 result.obligations.drain_filter(|projected_obligation| {
1083 if !deduped.insert(projected_obligation.clone()) {
1090 infcx.inner.borrow_mut().projection_cache().insert_term(cache_key, result.clone());
1092 obligations.extend(result.obligations);
1093 Ok(Some(result.value))
1095 Ok(Projected::NoProgress(projected_ty)) => {
1096 let result = Normalized { value: projected_ty, obligations: vec![] };
1098 infcx.inner.borrow_mut().projection_cache().insert_term(cache_key, result.clone());
1100 // No need to extend `obligations`.
1101 Ok(Some(result.value))
1103 Err(ProjectionError::TooManyCandidates) => {
1104 debug!("opt_normalize_projection_type: too many candidates");
1106 infcx.inner.borrow_mut().projection_cache().ambiguous(cache_key);
1110 Err(ProjectionError::TraitSelectionError(_)) => {
1111 debug!("opt_normalize_projection_type: ERROR");
1112 // if we got an error processing the `T as Trait` part,
1113 // just return `ty::err` but add the obligation `T :
1114 // Trait`, which when processed will cause the error to be
1118 infcx.inner.borrow_mut().projection_cache().error(cache_key);
1120 let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth);
1121 obligations.extend(result.obligations);
1122 Ok(Some(result.value.into()))
1127 /// If we are projecting `<T as Trait>::Item`, but `T: Trait` does not
1128 /// hold. In various error cases, we cannot generate a valid
1129 /// normalized projection. Therefore, we create an inference variable
1130 /// return an associated obligation that, when fulfilled, will lead to
1133 /// Note that we used to return `Error` here, but that was quite
1134 /// dubious -- the premise was that an error would *eventually* be
1135 /// reported, when the obligation was processed. But in general once
1136 /// you see an `Error` you are supposed to be able to assume that an
1137 /// error *has been* reported, so that you can take whatever heuristic
1138 /// paths you want to take. To make things worse, it was possible for
1139 /// cycles to arise, where you basically had a setup like `<MyType<$0>
1140 /// as Trait>::Foo == $0`. Here, normalizing `<MyType<$0> as
1141 /// Trait>::Foo> to `[type error]` would lead to an obligation of
1142 /// `<MyType<[type error]> as Trait>::Foo`. We are supposed to report
1143 /// an error for this obligation, but we legitimately should not,
1144 /// because it contains `[type error]`. Yuck! (See issue #29857 for
1145 /// one case where this arose.)
1146 fn normalize_to_error<'a, 'tcx>(
1147 selcx: &mut SelectionContext<'a, 'tcx>,
1148 param_env: ty::ParamEnv<'tcx>,
1149 projection_ty: ty::ProjectionTy<'tcx>,
1150 cause: ObligationCause<'tcx>,
1152 ) -> NormalizedTy<'tcx> {
1153 let trait_ref = ty::Binder::dummy(projection_ty.trait_ref(selcx.tcx()));
1154 let trait_obligation = Obligation {
1156 recursion_depth: depth,
1158 predicate: trait_ref.without_const().to_predicate(selcx.tcx()),
1160 let tcx = selcx.infcx().tcx;
1161 let def_id = projection_ty.item_def_id;
1162 let new_value = selcx.infcx().next_ty_var(TypeVariableOrigin {
1163 kind: TypeVariableOriginKind::NormalizeProjectionType,
1164 span: tcx.def_span(def_id),
1166 Normalized { value: new_value, obligations: vec![trait_obligation] }
1169 enum Projected<'tcx> {
1170 Progress(Progress<'tcx>),
1171 NoProgress(ty::Term<'tcx>),
1174 struct Progress<'tcx> {
1175 term: ty::Term<'tcx>,
1176 obligations: Vec<PredicateObligation<'tcx>>,
1179 impl<'tcx> Progress<'tcx> {
1180 fn error(tcx: TyCtxt<'tcx>) -> Self {
1181 Progress { term: tcx.ty_error().into(), obligations: vec![] }
1184 fn with_addl_obligations(mut self, mut obligations: Vec<PredicateObligation<'tcx>>) -> Self {
1185 self.obligations.append(&mut obligations);
1190 /// Computes the result of a projection type (if we can).
1193 /// - `obligation` must be fully normalized
1194 #[tracing::instrument(level = "info", skip(selcx))]
1195 fn project<'cx, 'tcx>(
1196 selcx: &mut SelectionContext<'cx, 'tcx>,
1197 obligation: &ProjectionTyObligation<'tcx>,
1198 ) -> Result<Projected<'tcx>, ProjectionError<'tcx>> {
1199 if !selcx.tcx().recursion_limit().value_within_limit(obligation.recursion_depth) {
1200 // This should really be an immediate error, but some existing code
1201 // relies on being able to recover from this.
1202 return Err(ProjectionError::TraitSelectionError(SelectionError::Overflow(
1203 OverflowError::Canonical,
1207 if obligation.predicate.references_error() {
1208 return Ok(Projected::Progress(Progress::error(selcx.tcx())));
1211 let mut candidates = ProjectionCandidateSet::None;
1213 // Make sure that the following procedures are kept in order. ParamEnv
1214 // needs to be first because it has highest priority, and Select checks
1215 // the return value of push_candidate which assumes it's ran at last.
1216 assemble_candidates_from_param_env(selcx, obligation, &mut candidates);
1218 assemble_candidates_from_trait_def(selcx, obligation, &mut candidates);
1220 assemble_candidates_from_object_ty(selcx, obligation, &mut candidates);
1222 if let ProjectionCandidateSet::Single(ProjectionCandidate::Object(_)) = candidates {
1223 // Avoid normalization cycle from selection (see
1224 // `assemble_candidates_from_object_ty`).
1225 // FIXME(lazy_normalization): Lazy normalization should save us from
1226 // having to special case this.
1228 assemble_candidates_from_impls(selcx, obligation, &mut candidates);
1232 ProjectionCandidateSet::Single(candidate) => {
1233 Ok(Projected::Progress(confirm_candidate(selcx, obligation, candidate)))
1235 ProjectionCandidateSet::None => Ok(Projected::NoProgress(
1236 // FIXME(associated_const_generics): this may need to change in the future?
1237 // need to investigate whether or not this is fine.
1240 .mk_projection(obligation.predicate.item_def_id, obligation.predicate.substs)
1243 // Error occurred while trying to processing impls.
1244 ProjectionCandidateSet::Error(e) => Err(ProjectionError::TraitSelectionError(e)),
1245 // Inherent ambiguity that prevents us from even enumerating the
1247 ProjectionCandidateSet::Ambiguous => Err(ProjectionError::TooManyCandidates),
1251 /// The first thing we have to do is scan through the parameter
1252 /// environment to see whether there are any projection predicates
1253 /// there that can answer this question.
1254 fn assemble_candidates_from_param_env<'cx, 'tcx>(
1255 selcx: &mut SelectionContext<'cx, 'tcx>,
1256 obligation: &ProjectionTyObligation<'tcx>,
1257 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1259 assemble_candidates_from_predicates(
1263 ProjectionCandidate::ParamEnv,
1264 obligation.param_env.caller_bounds().iter(),
1269 /// In the case of a nested projection like <<A as Foo>::FooT as Bar>::BarT, we may find
1270 /// that the definition of `Foo` has some clues:
1272 /// ```ignore (illustrative)
1274 /// type FooT : Bar<BarT=i32>
1278 /// Here, for example, we could conclude that the result is `i32`.
1279 fn assemble_candidates_from_trait_def<'cx, 'tcx>(
1280 selcx: &mut SelectionContext<'cx, 'tcx>,
1281 obligation: &ProjectionTyObligation<'tcx>,
1282 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1284 debug!("assemble_candidates_from_trait_def(..)");
1286 let tcx = selcx.tcx();
1287 // Check whether the self-type is itself a projection.
1288 // If so, extract what we know from the trait and try to come up with a good answer.
1289 let bounds = match *obligation.predicate.self_ty().kind() {
1290 ty::Projection(ref data) => tcx.bound_item_bounds(data.item_def_id).subst(tcx, data.substs),
1291 ty::Opaque(def_id, substs) => tcx.bound_item_bounds(def_id).subst(tcx, substs),
1292 ty::Infer(ty::TyVar(_)) => {
1293 // If the self-type is an inference variable, then it MAY wind up
1294 // being a projected type, so induce an ambiguity.
1295 candidate_set.mark_ambiguous();
1301 assemble_candidates_from_predicates(
1305 ProjectionCandidate::TraitDef,
1311 /// In the case of a trait object like
1312 /// `<dyn Iterator<Item = ()> as Iterator>::Item` we can use the existential
1313 /// predicate in the trait object.
1315 /// We don't go through the select candidate for these bounds to avoid cycles:
1316 /// In the above case, `dyn Iterator<Item = ()>: Iterator` would create a
1317 /// nested obligation of `<dyn Iterator<Item = ()> as Iterator>::Item: Sized`,
1318 /// this then has to be normalized without having to prove
1319 /// `dyn Iterator<Item = ()>: Iterator` again.
1320 fn assemble_candidates_from_object_ty<'cx, 'tcx>(
1321 selcx: &mut SelectionContext<'cx, 'tcx>,
1322 obligation: &ProjectionTyObligation<'tcx>,
1323 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1325 debug!("assemble_candidates_from_object_ty(..)");
1327 let tcx = selcx.tcx();
1329 let self_ty = obligation.predicate.self_ty();
1330 let object_ty = selcx.infcx().shallow_resolve(self_ty);
1331 let data = match object_ty.kind() {
1332 ty::Dynamic(data, ..) => data,
1333 ty::Infer(ty::TyVar(_)) => {
1334 // If the self-type is an inference variable, then it MAY wind up
1335 // being an object type, so induce an ambiguity.
1336 candidate_set.mark_ambiguous();
1341 let env_predicates = data
1342 .projection_bounds()
1343 .filter(|bound| bound.item_def_id() == obligation.predicate.item_def_id)
1344 .map(|p| p.with_self_ty(tcx, object_ty).to_predicate(tcx));
1346 assemble_candidates_from_predicates(
1350 ProjectionCandidate::Object,
1356 #[tracing::instrument(
1358 skip(selcx, candidate_set, ctor, env_predicates, potentially_unnormalized_candidates)
1360 fn assemble_candidates_from_predicates<'cx, 'tcx>(
1361 selcx: &mut SelectionContext<'cx, 'tcx>,
1362 obligation: &ProjectionTyObligation<'tcx>,
1363 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1364 ctor: fn(ty::PolyProjectionPredicate<'tcx>) -> ProjectionCandidate<'tcx>,
1365 env_predicates: impl Iterator<Item = ty::Predicate<'tcx>>,
1366 potentially_unnormalized_candidates: bool,
1368 let infcx = selcx.infcx();
1369 for predicate in env_predicates {
1370 let bound_predicate = predicate.kind();
1371 if let ty::PredicateKind::Projection(data) = predicate.kind().skip_binder() {
1372 let data = bound_predicate.rebind(data);
1373 if data.projection_def_id() != obligation.predicate.item_def_id {
1377 let is_match = infcx.probe(|_| {
1378 selcx.match_projection_projections(
1381 potentially_unnormalized_candidates,
1386 ProjectionMatchesProjection::Yes => {
1387 candidate_set.push_candidate(ctor(data));
1389 if potentially_unnormalized_candidates
1390 && !obligation.predicate.has_infer_types_or_consts()
1392 // HACK: Pick the first trait def candidate for a fully
1393 // inferred predicate. This is to allow duplicates that
1394 // differ only in normalization.
1398 ProjectionMatchesProjection::Ambiguous => {
1399 candidate_set.mark_ambiguous();
1401 ProjectionMatchesProjection::No => {}
1407 #[tracing::instrument(level = "debug", skip(selcx, obligation, candidate_set))]
1408 fn assemble_candidates_from_impls<'cx, 'tcx>(
1409 selcx: &mut SelectionContext<'cx, 'tcx>,
1410 obligation: &ProjectionTyObligation<'tcx>,
1411 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1413 // If we are resolving `<T as TraitRef<...>>::Item == Type`,
1414 // start out by selecting the predicate `T as TraitRef<...>`:
1415 let poly_trait_ref = ty::Binder::dummy(obligation.predicate.trait_ref(selcx.tcx()));
1416 let trait_obligation = obligation.with(poly_trait_ref.to_poly_trait_predicate());
1417 let _ = selcx.infcx().commit_if_ok(|_| {
1418 let impl_source = match selcx.select(&trait_obligation) {
1419 Ok(Some(impl_source)) => impl_source,
1421 candidate_set.mark_ambiguous();
1425 debug!(error = ?e, "selection error");
1426 candidate_set.mark_error(e);
1431 let eligible = match &impl_source {
1432 super::ImplSource::Closure(_)
1433 | super::ImplSource::Generator(_)
1434 | super::ImplSource::FnPointer(_)
1435 | super::ImplSource::TraitAlias(_) => true,
1436 super::ImplSource::UserDefined(impl_data) => {
1437 // We have to be careful when projecting out of an
1438 // impl because of specialization. If we are not in
1439 // codegen (i.e., projection mode is not "any"), and the
1440 // impl's type is declared as default, then we disable
1441 // projection (even if the trait ref is fully
1442 // monomorphic). In the case where trait ref is not
1443 // fully monomorphic (i.e., includes type parameters),
1444 // this is because those type parameters may
1445 // ultimately be bound to types from other crates that
1446 // may have specialized impls we can't see. In the
1447 // case where the trait ref IS fully monomorphic, this
1448 // is a policy decision that we made in the RFC in
1449 // order to preserve flexibility for the crate that
1450 // defined the specializable impl to specialize later
1451 // for existing types.
1453 // In either case, we handle this by not adding a
1454 // candidate for an impl if it contains a `default`
1457 // NOTE: This should be kept in sync with the similar code in
1458 // `rustc_ty_utils::instance::resolve_associated_item()`.
1460 assoc_def(selcx, impl_data.impl_def_id, obligation.predicate.item_def_id)
1461 .map_err(|ErrorGuaranteed { .. }| ())?;
1463 if node_item.is_final() {
1464 // Non-specializable items are always projectable.
1467 // Only reveal a specializable default if we're past type-checking
1468 // and the obligation is monomorphic, otherwise passes such as
1469 // transmute checking and polymorphic MIR optimizations could
1470 // get a result which isn't correct for all monomorphizations.
1471 if obligation.param_env.reveal() == Reveal::All {
1472 // NOTE(eddyb) inference variables can resolve to parameters, so
1473 // assume `poly_trait_ref` isn't monomorphic, if it contains any.
1474 let poly_trait_ref = selcx.infcx().resolve_vars_if_possible(poly_trait_ref);
1475 !poly_trait_ref.still_further_specializable()
1478 assoc_ty = ?selcx.tcx().def_path_str(node_item.item.def_id),
1479 ?obligation.predicate,
1480 "assemble_candidates_from_impls: not eligible due to default",
1486 super::ImplSource::DiscriminantKind(..) => {
1487 // While `DiscriminantKind` is automatically implemented for every type,
1488 // the concrete discriminant may not be known yet.
1490 // Any type with multiple potential discriminant types is therefore not eligible.
1491 let self_ty = selcx.infcx().shallow_resolve(obligation.predicate.self_ty());
1493 match self_ty.kind() {
1511 | ty::GeneratorWitness(..)
1514 // Integers and floats always have `u8` as their discriminant.
1515 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(..)) => true,
1521 | ty::Placeholder(..)
1523 | ty::Error(_) => false,
1526 super::ImplSource::Pointee(..) => {
1527 // While `Pointee` is automatically implemented for every type,
1528 // the concrete metadata type may not be known yet.
1530 // Any type with multiple potential metadata types is therefore not eligible.
1531 let self_ty = selcx.infcx().shallow_resolve(obligation.predicate.self_ty());
1533 let tail = selcx.tcx().struct_tail_with_normalize(
1536 // We throw away any obligations we get from this, since we normalize
1537 // and confirm these obligations once again during confirmation
1538 normalize_with_depth(
1540 obligation.param_env,
1541 obligation.cause.clone(),
1542 obligation.recursion_depth + 1,
1566 | ty::GeneratorWitness(..)
1568 // Extern types have unit metadata, according to RFC 2850
1570 // If returned by `struct_tail_without_normalization` this is a unit struct
1571 // without any fields, or not a struct, and therefore is Sized.
1573 // If returned by `struct_tail_without_normalization` this is the empty tuple.
1575 // Integers and floats are always Sized, and so have unit type metadata.
1576 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(..)) => true,
1578 // type parameters, opaques, and unnormalized projections have pointer
1579 // metadata if they're known (e.g. by the param_env) to be sized
1580 ty::Param(_) | ty::Projection(..) | ty::Opaque(..)
1581 if selcx.infcx().predicate_must_hold_modulo_regions(
1583 ty::Binder::dummy(ty::TraitRef::new(
1584 selcx.tcx().require_lang_item(LangItem::Sized, None),
1585 selcx.tcx().mk_substs_trait(self_ty, &[]),
1588 .to_predicate(selcx.tcx()),
1595 // FIXME(compiler-errors): are Bound and Placeholder types ever known sized?
1597 | ty::Projection(..)
1600 | ty::Placeholder(..)
1603 if tail.has_infer_types() {
1604 candidate_set.mark_ambiguous();
1610 super::ImplSource::Param(..) => {
1611 // This case tell us nothing about the value of an
1612 // associated type. Consider:
1615 // trait SomeTrait { type Foo; }
1616 // fn foo<T:SomeTrait>(...) { }
1619 // If the user writes `<T as SomeTrait>::Foo`, then the `T
1620 // : SomeTrait` binding does not help us decide what the
1621 // type `Foo` is (at least, not more specifically than
1622 // what we already knew).
1624 // But wait, you say! What about an example like this:
1627 // fn bar<T:SomeTrait<Foo=usize>>(...) { ... }
1630 // Doesn't the `T : SomeTrait<Foo=usize>` predicate help
1631 // resolve `T::Foo`? And of course it does, but in fact
1632 // that single predicate is desugared into two predicates
1633 // in the compiler: a trait predicate (`T : SomeTrait`) and a
1634 // projection. And the projection where clause is handled
1635 // in `assemble_candidates_from_param_env`.
1638 super::ImplSource::Object(_) => {
1639 // Handled by the `Object` projection candidate. See
1640 // `assemble_candidates_from_object_ty` for an explanation of
1641 // why we special case object types.
1644 super::ImplSource::AutoImpl(..)
1645 | super::ImplSource::Builtin(..)
1646 | super::ImplSource::TraitUpcasting(_)
1647 | super::ImplSource::ConstDestruct(_) => {
1648 // These traits have no associated types.
1649 selcx.tcx().sess.delay_span_bug(
1650 obligation.cause.span,
1651 &format!("Cannot project an associated type from `{:?}`", impl_source),
1658 if candidate_set.push_candidate(ProjectionCandidate::Select(impl_source)) {
1669 fn confirm_candidate<'cx, 'tcx>(
1670 selcx: &mut SelectionContext<'cx, 'tcx>,
1671 obligation: &ProjectionTyObligation<'tcx>,
1672 candidate: ProjectionCandidate<'tcx>,
1673 ) -> Progress<'tcx> {
1674 debug!(?obligation, ?candidate, "confirm_candidate");
1675 let mut progress = match candidate {
1676 ProjectionCandidate::ParamEnv(poly_projection)
1677 | ProjectionCandidate::Object(poly_projection) => {
1678 confirm_param_env_candidate(selcx, obligation, poly_projection, false)
1681 ProjectionCandidate::TraitDef(poly_projection) => {
1682 confirm_param_env_candidate(selcx, obligation, poly_projection, true)
1685 ProjectionCandidate::Select(impl_source) => {
1686 confirm_select_candidate(selcx, obligation, impl_source)
1690 // When checking for cycle during evaluation, we compare predicates with
1691 // "syntactic" equality. Since normalization generally introduces a type
1692 // with new region variables, we need to resolve them to existing variables
1693 // when possible for this to work. See `auto-trait-projection-recursion.rs`
1694 // for a case where this matters.
1695 if progress.term.has_infer_regions() {
1697 progress.term.fold_with(&mut OpportunisticRegionResolver::new(selcx.infcx()));
1702 fn confirm_select_candidate<'cx, 'tcx>(
1703 selcx: &mut SelectionContext<'cx, 'tcx>,
1704 obligation: &ProjectionTyObligation<'tcx>,
1705 impl_source: Selection<'tcx>,
1706 ) -> Progress<'tcx> {
1708 super::ImplSource::UserDefined(data) => confirm_impl_candidate(selcx, obligation, data),
1709 super::ImplSource::Generator(data) => confirm_generator_candidate(selcx, obligation, data),
1710 super::ImplSource::Closure(data) => confirm_closure_candidate(selcx, obligation, data),
1711 super::ImplSource::FnPointer(data) => confirm_fn_pointer_candidate(selcx, obligation, data),
1712 super::ImplSource::DiscriminantKind(data) => {
1713 confirm_discriminant_kind_candidate(selcx, obligation, data)
1715 super::ImplSource::Pointee(data) => confirm_pointee_candidate(selcx, obligation, data),
1716 super::ImplSource::Object(_)
1717 | super::ImplSource::AutoImpl(..)
1718 | super::ImplSource::Param(..)
1719 | super::ImplSource::Builtin(..)
1720 | super::ImplSource::TraitUpcasting(_)
1721 | super::ImplSource::TraitAlias(..)
1722 | super::ImplSource::ConstDestruct(_) => {
1723 // we don't create Select candidates with this kind of resolution
1725 obligation.cause.span,
1726 "Cannot project an associated type from `{:?}`",
1733 fn confirm_generator_candidate<'cx, 'tcx>(
1734 selcx: &mut SelectionContext<'cx, 'tcx>,
1735 obligation: &ProjectionTyObligation<'tcx>,
1736 impl_source: ImplSourceGeneratorData<'tcx, PredicateObligation<'tcx>>,
1737 ) -> Progress<'tcx> {
1738 let gen_sig = impl_source.substs.as_generator().poly_sig();
1739 let Normalized { value: gen_sig, obligations } = normalize_with_depth(
1741 obligation.param_env,
1742 obligation.cause.clone(),
1743 obligation.recursion_depth + 1,
1747 debug!(?obligation, ?gen_sig, ?obligations, "confirm_generator_candidate");
1749 let tcx = selcx.tcx();
1751 let gen_def_id = tcx.require_lang_item(LangItem::Generator, None);
1753 let predicate = super::util::generator_trait_ref_and_outputs(
1756 obligation.predicate.self_ty(),
1759 .map_bound(|(trait_ref, yield_ty, return_ty)| {
1760 let name = tcx.associated_item(obligation.predicate.item_def_id).name;
1761 let ty = if name == sym::Return {
1763 } else if name == sym::Yield {
1769 ty::ProjectionPredicate {
1770 projection_ty: ty::ProjectionTy {
1771 substs: trait_ref.substs,
1772 item_def_id: obligation.predicate.item_def_id,
1778 confirm_param_env_candidate(selcx, obligation, predicate, false)
1779 .with_addl_obligations(impl_source.nested)
1780 .with_addl_obligations(obligations)
1783 fn confirm_discriminant_kind_candidate<'cx, 'tcx>(
1784 selcx: &mut SelectionContext<'cx, 'tcx>,
1785 obligation: &ProjectionTyObligation<'tcx>,
1786 _: ImplSourceDiscriminantKindData,
1787 ) -> Progress<'tcx> {
1788 let tcx = selcx.tcx();
1790 let self_ty = selcx.infcx().shallow_resolve(obligation.predicate.self_ty());
1791 // We get here from `poly_project_and_unify_type` which replaces bound vars
1792 // with placeholders
1793 debug_assert!(!self_ty.has_escaping_bound_vars());
1794 let substs = tcx.mk_substs([self_ty.into()].iter());
1796 let discriminant_def_id = tcx.require_lang_item(LangItem::Discriminant, None);
1798 let predicate = ty::ProjectionPredicate {
1799 projection_ty: ty::ProjectionTy { substs, item_def_id: discriminant_def_id },
1800 term: self_ty.discriminant_ty(tcx).into(),
1803 // We get here from `poly_project_and_unify_type` which replaces bound vars
1804 // with placeholders, so dummy is okay here.
1805 confirm_param_env_candidate(selcx, obligation, ty::Binder::dummy(predicate), false)
1808 fn confirm_pointee_candidate<'cx, 'tcx>(
1809 selcx: &mut SelectionContext<'cx, 'tcx>,
1810 obligation: &ProjectionTyObligation<'tcx>,
1811 _: ImplSourcePointeeData,
1812 ) -> Progress<'tcx> {
1813 let tcx = selcx.tcx();
1814 let self_ty = selcx.infcx().shallow_resolve(obligation.predicate.self_ty());
1816 let mut obligations = vec![];
1817 let (metadata_ty, check_is_sized) = self_ty.ptr_metadata_ty(tcx, |ty| {
1818 normalize_with_depth_to(
1820 obligation.param_env,
1821 obligation.cause.clone(),
1822 obligation.recursion_depth + 1,
1828 let sized_predicate = ty::Binder::dummy(ty::TraitRef::new(
1829 tcx.require_lang_item(LangItem::Sized, None),
1830 tcx.mk_substs_trait(self_ty, &[]),
1834 obligations.push(Obligation::new(
1835 obligation.cause.clone(),
1836 obligation.param_env,
1841 let substs = tcx.mk_substs([self_ty.into()].iter());
1842 let metadata_def_id = tcx.require_lang_item(LangItem::Metadata, None);
1844 let predicate = ty::ProjectionPredicate {
1845 projection_ty: ty::ProjectionTy { substs, item_def_id: metadata_def_id },
1846 term: metadata_ty.into(),
1849 confirm_param_env_candidate(selcx, obligation, ty::Binder::dummy(predicate), false)
1850 .with_addl_obligations(obligations)
1853 fn confirm_fn_pointer_candidate<'cx, 'tcx>(
1854 selcx: &mut SelectionContext<'cx, 'tcx>,
1855 obligation: &ProjectionTyObligation<'tcx>,
1856 fn_pointer_impl_source: ImplSourceFnPointerData<'tcx, PredicateObligation<'tcx>>,
1857 ) -> Progress<'tcx> {
1858 let fn_type = selcx.infcx().shallow_resolve(fn_pointer_impl_source.fn_ty);
1859 let sig = fn_type.fn_sig(selcx.tcx());
1860 let Normalized { value: sig, obligations } = normalize_with_depth(
1862 obligation.param_env,
1863 obligation.cause.clone(),
1864 obligation.recursion_depth + 1,
1868 confirm_callable_candidate(selcx, obligation, sig, util::TupleArgumentsFlag::Yes)
1869 .with_addl_obligations(fn_pointer_impl_source.nested)
1870 .with_addl_obligations(obligations)
1873 fn confirm_closure_candidate<'cx, 'tcx>(
1874 selcx: &mut SelectionContext<'cx, 'tcx>,
1875 obligation: &ProjectionTyObligation<'tcx>,
1876 impl_source: ImplSourceClosureData<'tcx, PredicateObligation<'tcx>>,
1877 ) -> Progress<'tcx> {
1878 let closure_sig = impl_source.substs.as_closure().sig();
1879 let Normalized { value: closure_sig, obligations } = normalize_with_depth(
1881 obligation.param_env,
1882 obligation.cause.clone(),
1883 obligation.recursion_depth + 1,
1887 debug!(?obligation, ?closure_sig, ?obligations, "confirm_closure_candidate");
1889 confirm_callable_candidate(selcx, obligation, closure_sig, util::TupleArgumentsFlag::No)
1890 .with_addl_obligations(impl_source.nested)
1891 .with_addl_obligations(obligations)
1894 fn confirm_callable_candidate<'cx, 'tcx>(
1895 selcx: &mut SelectionContext<'cx, 'tcx>,
1896 obligation: &ProjectionTyObligation<'tcx>,
1897 fn_sig: ty::PolyFnSig<'tcx>,
1898 flag: util::TupleArgumentsFlag,
1899 ) -> Progress<'tcx> {
1900 let tcx = selcx.tcx();
1902 debug!(?obligation, ?fn_sig, "confirm_callable_candidate");
1904 let fn_once_def_id = tcx.require_lang_item(LangItem::FnOnce, None);
1905 let fn_once_output_def_id = tcx.require_lang_item(LangItem::FnOnceOutput, None);
1907 let predicate = super::util::closure_trait_ref_and_return_type(
1910 obligation.predicate.self_ty(),
1914 .map_bound(|(trait_ref, ret_type)| ty::ProjectionPredicate {
1915 projection_ty: ty::ProjectionTy {
1916 substs: trait_ref.substs,
1917 item_def_id: fn_once_output_def_id,
1919 term: ret_type.into(),
1922 confirm_param_env_candidate(selcx, obligation, predicate, true)
1925 fn confirm_param_env_candidate<'cx, 'tcx>(
1926 selcx: &mut SelectionContext<'cx, 'tcx>,
1927 obligation: &ProjectionTyObligation<'tcx>,
1928 poly_cache_entry: ty::PolyProjectionPredicate<'tcx>,
1929 potentially_unnormalized_candidate: bool,
1930 ) -> Progress<'tcx> {
1931 let infcx = selcx.infcx();
1932 let cause = &obligation.cause;
1933 let param_env = obligation.param_env;
1935 let cache_entry = infcx.replace_bound_vars_with_fresh_vars(
1937 LateBoundRegionConversionTime::HigherRankedType,
1941 let cache_projection = cache_entry.projection_ty;
1942 let mut nested_obligations = Vec::new();
1943 let obligation_projection = obligation.predicate;
1944 let obligation_projection = ensure_sufficient_stack(|| {
1945 normalize_with_depth_to(
1947 obligation.param_env,
1948 obligation.cause.clone(),
1949 obligation.recursion_depth + 1,
1950 obligation_projection,
1951 &mut nested_obligations,
1954 let cache_projection = if potentially_unnormalized_candidate {
1955 ensure_sufficient_stack(|| {
1956 normalize_with_depth_to(
1958 obligation.param_env,
1959 obligation.cause.clone(),
1960 obligation.recursion_depth + 1,
1962 &mut nested_obligations,
1969 debug!(?cache_projection, ?obligation_projection);
1971 match infcx.at(cause, param_env).eq(cache_projection, obligation_projection) {
1972 Ok(InferOk { value: _, obligations }) => {
1973 nested_obligations.extend(obligations);
1974 assoc_ty_own_obligations(selcx, obligation, &mut nested_obligations);
1975 // FIXME(associated_const_equality): Handle consts here as well? Maybe this progress type should just take
1977 Progress { term: cache_entry.term, obligations: nested_obligations }
1981 "Failed to unify obligation `{:?}` with poly_projection `{:?}`: {:?}",
1982 obligation, poly_cache_entry, e,
1984 debug!("confirm_param_env_candidate: {}", msg);
1985 let err = infcx.tcx.ty_error_with_message(obligation.cause.span, &msg);
1986 Progress { term: err.into(), obligations: vec![] }
1991 fn confirm_impl_candidate<'cx, 'tcx>(
1992 selcx: &mut SelectionContext<'cx, 'tcx>,
1993 obligation: &ProjectionTyObligation<'tcx>,
1994 impl_impl_source: ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>>,
1995 ) -> Progress<'tcx> {
1996 let tcx = selcx.tcx();
1998 let ImplSourceUserDefinedData { impl_def_id, substs, mut nested } = impl_impl_source;
1999 let assoc_item_id = obligation.predicate.item_def_id;
2000 let trait_def_id = tcx.trait_id_of_impl(impl_def_id).unwrap();
2002 let param_env = obligation.param_env;
2003 let Ok(assoc_ty) = assoc_def(selcx, impl_def_id, assoc_item_id) else {
2004 return Progress { term: tcx.ty_error().into(), obligations: nested };
2007 if !assoc_ty.item.defaultness(tcx).has_value() {
2008 // This means that the impl is missing a definition for the
2009 // associated type. This error will be reported by the type
2010 // checker method `check_impl_items_against_trait`, so here we
2011 // just return Error.
2013 "confirm_impl_candidate: no associated type {:?} for {:?}",
2014 assoc_ty.item.name, obligation.predicate
2016 return Progress { term: tcx.ty_error().into(), obligations: nested };
2018 // If we're trying to normalize `<Vec<u32> as X>::A<S>` using
2019 //`impl<T> X for Vec<T> { type A<Y> = Box<Y>; }`, then:
2021 // * `obligation.predicate.substs` is `[Vec<u32>, S]`
2022 // * `substs` is `[u32]`
2023 // * `substs` ends up as `[u32, S]`
2024 let substs = obligation.predicate.substs.rebase_onto(tcx, trait_def_id, substs);
2026 translate_substs(selcx.infcx(), param_env, impl_def_id, substs, assoc_ty.defining_node);
2027 let ty = tcx.bound_type_of(assoc_ty.item.def_id);
2028 let is_const = matches!(tcx.def_kind(assoc_ty.item.def_id), DefKind::AssocConst);
2029 let term: ty::EarlyBinder<ty::Term<'tcx>> = if is_const {
2030 let identity_substs =
2031 crate::traits::InternalSubsts::identity_for_item(tcx, assoc_ty.item.def_id);
2032 let did = ty::WithOptConstParam::unknown(assoc_ty.item.def_id);
2033 let kind = ty::ConstKind::Unevaluated(ty::Unevaluated::new(did, identity_substs));
2034 ty.map_bound(|ty| tcx.mk_const(ty::ConstS { ty, kind }).into())
2036 ty.map_bound(|ty| ty.into())
2038 if substs.len() != tcx.generics_of(assoc_ty.item.def_id).count() {
2039 let err = tcx.ty_error_with_message(
2040 obligation.cause.span,
2041 "impl item and trait item have different parameter counts",
2043 Progress { term: err.into(), obligations: nested }
2045 assoc_ty_own_obligations(selcx, obligation, &mut nested);
2046 Progress { term: term.subst(tcx, substs), obligations: nested }
2050 // Get obligations corresponding to the predicates from the where-clause of the
2051 // associated type itself.
2052 // Note: `feature(generic_associated_types)` is required to write such
2053 // predicates, even for non-generic associated types.
2054 fn assoc_ty_own_obligations<'cx, 'tcx>(
2055 selcx: &mut SelectionContext<'cx, 'tcx>,
2056 obligation: &ProjectionTyObligation<'tcx>,
2057 nested: &mut Vec<PredicateObligation<'tcx>>,
2059 let tcx = selcx.tcx();
2060 for predicate in tcx
2061 .predicates_of(obligation.predicate.item_def_id)
2062 .instantiate_own(tcx, obligation.predicate.substs)
2065 let normalized = normalize_with_depth_to(
2067 obligation.param_env,
2068 obligation.cause.clone(),
2069 obligation.recursion_depth + 1,
2073 nested.push(Obligation::with_depth(
2074 obligation.cause.clone(),
2075 obligation.recursion_depth + 1,
2076 obligation.param_env,
2082 /// Locate the definition of an associated type in the specialization hierarchy,
2083 /// starting from the given impl.
2085 /// Based on the "projection mode", this lookup may in fact only examine the
2086 /// topmost impl. See the comments for `Reveal` for more details.
2088 selcx: &SelectionContext<'_, '_>,
2090 assoc_def_id: DefId,
2091 ) -> Result<specialization_graph::LeafDef, ErrorGuaranteed> {
2092 let tcx = selcx.tcx();
2093 let trait_def_id = tcx.impl_trait_ref(impl_def_id).unwrap().def_id;
2094 let trait_def = tcx.trait_def(trait_def_id);
2096 // This function may be called while we are still building the
2097 // specialization graph that is queried below (via TraitDef::ancestors()),
2098 // so, in order to avoid unnecessary infinite recursion, we manually look
2099 // for the associated item at the given impl.
2100 // If there is no such item in that impl, this function will fail with a
2101 // cycle error if the specialization graph is currently being built.
2102 if let Some(&impl_item_id) = tcx.impl_item_implementor_ids(impl_def_id).get(&assoc_def_id) {
2103 let item = tcx.associated_item(impl_item_id);
2104 let impl_node = specialization_graph::Node::Impl(impl_def_id);
2105 return Ok(specialization_graph::LeafDef {
2107 defining_node: impl_node,
2108 finalizing_node: if item.defaultness(tcx).is_default() {
2116 let ancestors = trait_def.ancestors(tcx, impl_def_id)?;
2117 if let Some(assoc_item) = ancestors.leaf_def(tcx, assoc_def_id) {
2120 // This is saying that neither the trait nor
2121 // the impl contain a definition for this
2122 // associated type. Normally this situation
2123 // could only arise through a compiler bug --
2124 // if the user wrote a bad item name, it
2125 // should have failed in astconv.
2127 "No associated type `{}` for {}",
2128 tcx.item_name(assoc_def_id),
2129 tcx.def_path_str(impl_def_id)
2134 pub(crate) trait ProjectionCacheKeyExt<'cx, 'tcx>: Sized {
2135 fn from_poly_projection_predicate(
2136 selcx: &mut SelectionContext<'cx, 'tcx>,
2137 predicate: ty::PolyProjectionPredicate<'tcx>,
2141 impl<'cx, 'tcx> ProjectionCacheKeyExt<'cx, 'tcx> for ProjectionCacheKey<'tcx> {
2142 fn from_poly_projection_predicate(
2143 selcx: &mut SelectionContext<'cx, 'tcx>,
2144 predicate: ty::PolyProjectionPredicate<'tcx>,
2146 let infcx = selcx.infcx();
2147 // We don't do cross-snapshot caching of obligations with escaping regions,
2148 // so there's no cache key to use
2149 predicate.no_bound_vars().map(|predicate| {
2150 ProjectionCacheKey::new(
2151 // We don't attempt to match up with a specific type-variable state
2152 // from a specific call to `opt_normalize_projection_type` - if
2153 // there's no precise match, the original cache entry is "stranded"
2155 infcx.resolve_vars_if_possible(predicate.projection_ty),