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, ImplSourceFnPointerData, ImplSourceFutureData, ImplSourceGeneratorData,
15 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::TypeErrCtxtExt 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::at::At;
31 use rustc_infer::infer::resolve::OpportunisticRegionResolver;
32 use rustc_infer::traits::ImplSourceBuiltinData;
33 use rustc_middle::traits::select::OverflowError;
34 use rustc_middle::ty::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable};
35 use rustc_middle::ty::visit::{MaxUniverse, TypeVisitable};
36 use rustc_middle::ty::DefIdTree;
37 use rustc_middle::ty::{self, Term, ToPredicate, Ty, TyCtxt};
38 use rustc_span::symbol::sym;
40 use std::collections::BTreeMap;
42 pub use rustc_middle::traits::Reveal;
44 pub type PolyProjectionObligation<'tcx> = Obligation<'tcx, ty::PolyProjectionPredicate<'tcx>>;
46 pub type ProjectionObligation<'tcx> = Obligation<'tcx, ty::ProjectionPredicate<'tcx>>;
48 pub type ProjectionTyObligation<'tcx> = Obligation<'tcx, ty::ProjectionTy<'tcx>>;
50 pub(super) struct InProgress;
52 pub trait NormalizeExt<'tcx> {
53 /// Normalize a value using the `AssocTypeNormalizer`.
55 /// This normalization should be used when the type contains inference variables or the
56 /// projection may be fallible.
57 fn normalize<T: TypeFoldable<'tcx>>(&self, t: T) -> InferOk<'tcx, T>;
60 impl<'tcx> NormalizeExt<'tcx> for At<'_, 'tcx> {
61 fn normalize<T: TypeFoldable<'tcx>>(&self, value: T) -> InferOk<'tcx, T> {
62 let mut selcx = SelectionContext::new(self.infcx);
63 let Normalized { value, obligations } =
64 normalize_with_depth(&mut selcx, self.param_env, self.cause.clone(), 0, value);
65 InferOk { value, obligations }
69 /// When attempting to resolve `<T as TraitRef>::Name` ...
71 pub enum ProjectionError<'tcx> {
72 /// ...we found multiple sources of information and couldn't resolve the ambiguity.
75 /// ...an error occurred matching `T : TraitRef`
76 TraitSelectionError(SelectionError<'tcx>),
79 #[derive(PartialEq, Eq, Debug)]
80 enum ProjectionCandidate<'tcx> {
81 /// From a where-clause in the env or object type
82 ParamEnv(ty::PolyProjectionPredicate<'tcx>),
84 /// From the definition of `Trait` when you have something like
85 /// `<<A as Trait>::B as Trait2>::C`.
86 TraitDef(ty::PolyProjectionPredicate<'tcx>),
88 /// Bounds specified on an object type
89 Object(ty::PolyProjectionPredicate<'tcx>),
91 /// From an "impl" (or a "pseudo-impl" returned by select)
92 Select(Selection<'tcx>),
94 ImplTraitInTrait(ImplTraitInTraitCandidate<'tcx>),
97 #[derive(PartialEq, Eq, Debug)]
98 enum ImplTraitInTraitCandidate<'tcx> {
99 // The `impl Trait` from a trait function's default body
101 // A concrete type provided from a trait's `impl Trait` from an impl
102 Impl(ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>>),
105 enum ProjectionCandidateSet<'tcx> {
107 Single(ProjectionCandidate<'tcx>),
109 Error(SelectionError<'tcx>),
112 impl<'tcx> ProjectionCandidateSet<'tcx> {
113 fn mark_ambiguous(&mut self) {
114 *self = ProjectionCandidateSet::Ambiguous;
117 fn mark_error(&mut self, err: SelectionError<'tcx>) {
118 *self = ProjectionCandidateSet::Error(err);
121 // Returns true if the push was successful, or false if the candidate
122 // was discarded -- this could be because of ambiguity, or because
123 // a higher-priority candidate is already there.
124 fn push_candidate(&mut self, candidate: ProjectionCandidate<'tcx>) -> bool {
125 use self::ProjectionCandidate::*;
126 use self::ProjectionCandidateSet::*;
128 // This wacky variable is just used to try and
129 // make code readable and avoid confusing paths.
130 // It is assigned a "value" of `()` only on those
131 // paths in which we wish to convert `*self` to
132 // ambiguous (and return false, because the candidate
133 // was not used). On other paths, it is not assigned,
134 // and hence if those paths *could* reach the code that
135 // comes after the match, this fn would not compile.
136 let convert_to_ambiguous;
140 *self = Single(candidate);
145 // Duplicates can happen inside ParamEnv. In the case, we
146 // perform a lazy deduplication.
147 if current == &candidate {
151 // Prefer where-clauses. As in select, if there are multiple
152 // candidates, we prefer where-clause candidates over impls. This
153 // may seem a bit surprising, since impls are the source of
154 // "truth" in some sense, but in fact some of the impls that SEEM
155 // applicable are not, because of nested obligations. Where
156 // clauses are the safer choice. See the comment on
157 // `select::SelectionCandidate` and #21974 for more details.
158 match (current, candidate) {
159 (ParamEnv(..), ParamEnv(..)) => convert_to_ambiguous = (),
160 (ParamEnv(..), _) => return false,
161 (_, ParamEnv(..)) => unreachable!(),
162 (_, _) => convert_to_ambiguous = (),
166 Ambiguous | Error(..) => {
171 // We only ever get here when we moved from a single candidate
173 let () = convert_to_ambiguous;
179 /// States returned from `poly_project_and_unify_type`. Takes the place
180 /// of the old return type, which was:
181 /// ```ignore (not-rust)
183 /// Result<Option<Vec<PredicateObligation<'tcx>>>, InProgress>,
184 /// MismatchedProjectionTypes<'tcx>,
187 pub(super) enum ProjectAndUnifyResult<'tcx> {
188 /// The projection bound holds subject to the given obligations. If the
189 /// projection cannot be normalized because the required trait bound does
190 /// not hold, this is returned, with `obligations` being a predicate that
191 /// cannot be proven.
192 Holds(Vec<PredicateObligation<'tcx>>),
193 /// The projection cannot be normalized due to ambiguity. Resolving some
194 /// inference variables in the projection may fix this.
196 /// The project cannot be normalized because `poly_project_and_unify_type`
197 /// is called recursively while normalizing the same projection.
199 // the projection can be normalized, but is not equal to the expected type.
200 // Returns the type error that arose from the mismatch.
201 MismatchedProjectionTypes(MismatchedProjectionTypes<'tcx>),
204 /// Evaluates constraints of the form:
205 /// ```ignore (not-rust)
206 /// for<...> <T as Trait>::U == V
208 /// If successful, this may result in additional obligations. Also returns
209 /// the projection cache key used to track these additional obligations.
210 #[instrument(level = "debug", skip(selcx))]
211 pub(super) fn poly_project_and_unify_type<'cx, 'tcx>(
212 selcx: &mut SelectionContext<'cx, 'tcx>,
213 obligation: &PolyProjectionObligation<'tcx>,
214 ) -> ProjectAndUnifyResult<'tcx> {
215 let infcx = selcx.infcx;
216 let r = infcx.commit_if_ok(|_snapshot| {
217 let old_universe = infcx.universe();
218 let placeholder_predicate =
219 infcx.replace_bound_vars_with_placeholders(obligation.predicate);
220 let new_universe = infcx.universe();
222 let placeholder_obligation = obligation.with(infcx.tcx, placeholder_predicate);
223 match project_and_unify_type(selcx, &placeholder_obligation) {
224 ProjectAndUnifyResult::MismatchedProjectionTypes(e) => Err(e),
225 ProjectAndUnifyResult::Holds(obligations)
226 if old_universe != new_universe
227 && selcx.tcx().features().generic_associated_types_extended =>
229 // If the `generic_associated_types_extended` feature is active, then we ignore any
230 // obligations references lifetimes from any universe greater than or equal to the
231 // universe just created. Otherwise, we can end up with something like `for<'a> I: 'a`,
232 // which isn't quite what we want. Ideally, we want either an implied
233 // `for<'a where I: 'a> I: 'a` or we want to "lazily" check these hold when we
234 // substitute concrete regions. There is design work to be done here; until then,
235 // however, this allows experimenting potential GAT features without running into
236 // well-formedness issues.
237 let new_obligations = obligations
239 .filter(|obligation| {
240 let mut visitor = MaxUniverse::new();
241 obligation.predicate.visit_with(&mut visitor);
242 visitor.max_universe() < new_universe
245 Ok(ProjectAndUnifyResult::Holds(new_obligations))
253 Err(err) => ProjectAndUnifyResult::MismatchedProjectionTypes(err),
257 /// Evaluates constraints of the form:
258 /// ```ignore (not-rust)
259 /// <T as Trait>::U == V
261 /// If successful, this may result in additional obligations.
263 /// See [poly_project_and_unify_type] for an explanation of the return value.
264 #[instrument(level = "debug", skip(selcx))]
265 fn project_and_unify_type<'cx, 'tcx>(
266 selcx: &mut SelectionContext<'cx, 'tcx>,
267 obligation: &ProjectionObligation<'tcx>,
268 ) -> ProjectAndUnifyResult<'tcx> {
269 let mut obligations = vec![];
271 let infcx = selcx.infcx;
272 let normalized = match opt_normalize_projection_type(
274 obligation.param_env,
275 obligation.predicate.projection_ty,
276 obligation.cause.clone(),
277 obligation.recursion_depth,
281 Ok(None) => return ProjectAndUnifyResult::FailedNormalization,
282 Err(InProgress) => return ProjectAndUnifyResult::Recursive,
284 debug!(?normalized, ?obligations, "project_and_unify_type result");
285 let actual = obligation.predicate.term;
286 // For an example where this is necessary see src/test/ui/impl-trait/nested-return-type2.rs
287 // This allows users to omit re-mentioning all bounds on an associated type and just use an
288 // `impl Trait` for the assoc type to add more bounds.
289 let InferOk { value: actual, obligations: new } =
290 selcx.infcx.replace_opaque_types_with_inference_vars(
292 obligation.cause.body_id,
293 obligation.cause.span,
294 obligation.param_env,
296 obligations.extend(new);
298 match infcx.at(&obligation.cause, obligation.param_env).eq(normalized, actual) {
299 Ok(InferOk { obligations: inferred_obligations, value: () }) => {
300 obligations.extend(inferred_obligations);
301 ProjectAndUnifyResult::Holds(obligations)
304 debug!("equating types encountered error {:?}", err);
305 ProjectAndUnifyResult::MismatchedProjectionTypes(MismatchedProjectionTypes { err })
310 /// As `normalize`, but with a custom depth.
311 pub(crate) fn normalize_with_depth<'a, 'b, 'tcx, T>(
312 selcx: &'a mut SelectionContext<'b, 'tcx>,
313 param_env: ty::ParamEnv<'tcx>,
314 cause: ObligationCause<'tcx>,
317 ) -> Normalized<'tcx, T>
319 T: TypeFoldable<'tcx>,
321 let mut obligations = Vec::new();
322 let value = normalize_with_depth_to(selcx, param_env, cause, depth, value, &mut obligations);
323 Normalized { value, obligations }
326 #[instrument(level = "info", skip(selcx, param_env, cause, obligations))]
327 pub(crate) fn normalize_with_depth_to<'a, 'b, 'tcx, T>(
328 selcx: &'a mut SelectionContext<'b, 'tcx>,
329 param_env: ty::ParamEnv<'tcx>,
330 cause: ObligationCause<'tcx>,
333 obligations: &mut Vec<PredicateObligation<'tcx>>,
336 T: TypeFoldable<'tcx>,
338 debug!(obligations.len = obligations.len());
339 let mut normalizer = AssocTypeNormalizer::new(selcx, param_env, cause, depth, obligations);
340 let result = ensure_sufficient_stack(|| normalizer.fold(value));
341 debug!(?result, obligations.len = normalizer.obligations.len());
342 debug!(?normalizer.obligations,);
346 #[instrument(level = "info", skip(selcx, param_env, cause, obligations))]
347 pub(crate) fn try_normalize_with_depth_to<'a, 'b, 'tcx, T>(
348 selcx: &'a mut SelectionContext<'b, 'tcx>,
349 param_env: ty::ParamEnv<'tcx>,
350 cause: ObligationCause<'tcx>,
353 obligations: &mut Vec<PredicateObligation<'tcx>>,
356 T: TypeFoldable<'tcx>,
358 debug!(obligations.len = obligations.len());
359 let mut normalizer = AssocTypeNormalizer::new_without_eager_inference_replacement(
366 let result = ensure_sufficient_stack(|| normalizer.fold(value));
367 debug!(?result, obligations.len = normalizer.obligations.len());
368 debug!(?normalizer.obligations,);
372 pub(crate) fn needs_normalization<'tcx, T: TypeVisitable<'tcx>>(value: &T, reveal: Reveal) -> bool {
374 Reveal::UserFacing => value
375 .has_type_flags(ty::TypeFlags::HAS_TY_PROJECTION | ty::TypeFlags::HAS_CT_PROJECTION),
376 Reveal::All => value.has_type_flags(
377 ty::TypeFlags::HAS_TY_PROJECTION
378 | ty::TypeFlags::HAS_TY_OPAQUE
379 | ty::TypeFlags::HAS_CT_PROJECTION,
384 struct AssocTypeNormalizer<'a, 'b, 'tcx> {
385 selcx: &'a mut SelectionContext<'b, 'tcx>,
386 param_env: ty::ParamEnv<'tcx>,
387 cause: ObligationCause<'tcx>,
388 obligations: &'a mut Vec<PredicateObligation<'tcx>>,
390 universes: Vec<Option<ty::UniverseIndex>>,
391 /// If true, when a projection is unable to be completed, an inference
392 /// variable will be created and an obligation registered to project to that
393 /// inference variable. Also, constants will be eagerly evaluated.
394 eager_inference_replacement: bool,
397 impl<'a, 'b, 'tcx> AssocTypeNormalizer<'a, 'b, 'tcx> {
399 selcx: &'a mut SelectionContext<'b, 'tcx>,
400 param_env: ty::ParamEnv<'tcx>,
401 cause: ObligationCause<'tcx>,
403 obligations: &'a mut Vec<PredicateObligation<'tcx>>,
404 ) -> AssocTypeNormalizer<'a, 'b, 'tcx> {
405 AssocTypeNormalizer {
412 eager_inference_replacement: true,
416 fn new_without_eager_inference_replacement(
417 selcx: &'a mut SelectionContext<'b, 'tcx>,
418 param_env: ty::ParamEnv<'tcx>,
419 cause: ObligationCause<'tcx>,
421 obligations: &'a mut Vec<PredicateObligation<'tcx>>,
422 ) -> AssocTypeNormalizer<'a, 'b, 'tcx> {
423 AssocTypeNormalizer {
430 eager_inference_replacement: false,
434 fn fold<T: TypeFoldable<'tcx>>(&mut self, value: T) -> T {
435 let value = self.selcx.infcx.resolve_vars_if_possible(value);
439 !value.has_escaping_bound_vars(),
440 "Normalizing {:?} without wrapping in a `Binder`",
444 if !needs_normalization(&value, self.param_env.reveal()) {
447 value.fold_with(self)
452 impl<'a, 'b, 'tcx> TypeFolder<'tcx> for AssocTypeNormalizer<'a, 'b, 'tcx> {
453 fn tcx<'c>(&'c self) -> TyCtxt<'tcx> {
457 fn fold_binder<T: TypeFoldable<'tcx>>(
459 t: ty::Binder<'tcx, T>,
460 ) -> ty::Binder<'tcx, T> {
461 self.universes.push(None);
462 let t = t.super_fold_with(self);
463 self.universes.pop();
467 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
468 if !needs_normalization(&ty, self.param_env.reveal()) {
472 // We try to be a little clever here as a performance optimization in
473 // cases where there are nested projections under binders.
476 // for<'a> fn(<T as Foo>::One<'a, Box<dyn Bar<'a, Item=<T as Foo>::Two<'a>>>>)
478 // We normalize the substs on the projection before the projecting, but
479 // if we're naive, we'll
480 // replace bound vars on inner, project inner, replace placeholders on inner,
481 // replace bound vars on outer, project outer, replace placeholders on outer
483 // However, if we're a bit more clever, we can replace the bound vars
484 // on the entire type before normalizing nested projections, meaning we
485 // replace bound vars on outer, project inner,
486 // project outer, replace placeholders on outer
488 // This is possible because the inner `'a` will already be a placeholder
489 // when we need to normalize the inner projection
491 // On the other hand, this does add a bit of complexity, since we only
492 // replace bound vars if the current type is a `Projection` and we need
493 // to make sure we don't forget to fold the substs regardless.
496 // This is really important. While we *can* handle this, this has
497 // severe performance implications for large opaque types with
498 // late-bound regions. See `issue-88862` benchmark.
499 ty::Opaque(def_id, substs) if !substs.has_escaping_bound_vars() => {
500 // Only normalize `impl Trait` outside of type inference, usually in codegen.
501 match self.param_env.reveal() {
502 Reveal::UserFacing => ty.super_fold_with(self),
505 let recursion_limit = self.tcx().recursion_limit();
506 if !recursion_limit.value_within_limit(self.depth) {
507 let obligation = Obligation::with_depth(
514 self.selcx.infcx.err_ctxt().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.super_fold_with(self).into())
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 let tcx = self.selcx.tcx();
624 if tcx.lazy_normalization() || !needs_normalization(&constant, self.param_env.reveal()) {
627 let constant = constant.super_fold_with(self);
628 debug!(?constant, ?self.param_env);
629 with_replaced_escaping_bound_vars(
633 |constant| constant.eval(tcx, self.param_env),
639 fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
640 if p.allow_normalization() && needs_normalization(&p, self.param_env.reveal()) {
641 p.super_fold_with(self)
648 pub struct BoundVarReplacer<'me, 'tcx> {
649 infcx: &'me InferCtxt<'tcx>,
650 // These three maps track the bound variable that were replaced by placeholders. It might be
651 // nice to remove these since we already have the `kind` in the placeholder; we really just need
652 // the `var` (but we *could* bring that into scope if we were to track them as we pass them).
653 mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
654 mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy>,
655 mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
656 // The current depth relative to *this* folding, *not* the entire normalization. In other words,
657 // the depth of binders we've passed here.
658 current_index: ty::DebruijnIndex,
659 // The `UniverseIndex` of the binding levels above us. These are optional, since we are lazy:
660 // we don't actually create a universe until we see a bound var we have to replace.
661 universe_indices: &'me mut Vec<Option<ty::UniverseIndex>>,
664 /// Executes `f` on `value` after replacing all escaping bound variables with placeholders
665 /// and then replaces these placeholders with the original bound variables in the result.
667 /// In most places, bound variables should be replaced right when entering a binder, making
668 /// this function unnecessary. However, normalization currently does not do that, so we have
669 /// to do this lazily.
671 /// You should not add any additional uses of this function, at least not without first
672 /// discussing it with t-types.
674 /// FIXME(@lcnr): We may even consider experimenting with eagerly replacing bound vars during
675 /// normalization as well, at which point this function will be unnecessary and can be removed.
676 pub fn with_replaced_escaping_bound_vars<'a, 'tcx, T: TypeFoldable<'tcx>, R: TypeFoldable<'tcx>>(
677 infcx: &'a InferCtxt<'tcx>,
678 universe_indices: &'a mut Vec<Option<ty::UniverseIndex>>,
680 f: impl FnOnce(T) -> R,
682 if value.has_escaping_bound_vars() {
683 let (value, mapped_regions, mapped_types, mapped_consts) =
684 BoundVarReplacer::replace_bound_vars(infcx, universe_indices, value);
685 let result = f(value);
686 PlaceholderReplacer::replace_placeholders(
699 impl<'me, 'tcx> BoundVarReplacer<'me, 'tcx> {
700 /// Returns `Some` if we *were* able to replace bound vars. If there are any bound vars that
701 /// use a binding level above `universe_indices.len()`, we fail.
702 pub fn replace_bound_vars<T: TypeFoldable<'tcx>>(
703 infcx: &'me InferCtxt<'tcx>,
704 universe_indices: &'me mut Vec<Option<ty::UniverseIndex>>,
708 BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
709 BTreeMap<ty::PlaceholderType, ty::BoundTy>,
710 BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
712 let mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion> = BTreeMap::new();
713 let mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy> = BTreeMap::new();
714 let mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar> = BTreeMap::new();
716 let mut replacer = BoundVarReplacer {
721 current_index: ty::INNERMOST,
725 let value = value.fold_with(&mut replacer);
727 (value, replacer.mapped_regions, replacer.mapped_types, replacer.mapped_consts)
730 fn universe_for(&mut self, debruijn: ty::DebruijnIndex) -> ty::UniverseIndex {
731 let infcx = self.infcx;
733 self.universe_indices.len() + self.current_index.as_usize() - debruijn.as_usize() - 1;
734 let universe = self.universe_indices[index].unwrap_or_else(|| {
735 for i in self.universe_indices.iter_mut().take(index + 1) {
736 *i = i.or_else(|| Some(infcx.create_next_universe()))
738 self.universe_indices[index].unwrap()
744 impl<'tcx> TypeFolder<'tcx> for BoundVarReplacer<'_, 'tcx> {
745 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
749 fn fold_binder<T: TypeFoldable<'tcx>>(
751 t: ty::Binder<'tcx, T>,
752 ) -> ty::Binder<'tcx, T> {
753 self.current_index.shift_in(1);
754 let t = t.super_fold_with(self);
755 self.current_index.shift_out(1);
759 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
761 ty::ReLateBound(debruijn, _)
762 if debruijn.as_usize() + 1
763 > self.current_index.as_usize() + self.universe_indices.len() =>
765 bug!("Bound vars outside of `self.universe_indices`");
767 ty::ReLateBound(debruijn, br) if debruijn >= self.current_index => {
768 let universe = self.universe_for(debruijn);
769 let p = ty::PlaceholderRegion { universe, name: br.kind };
770 self.mapped_regions.insert(p, br);
771 self.infcx.tcx.mk_region(ty::RePlaceholder(p))
777 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
779 ty::Bound(debruijn, _)
780 if debruijn.as_usize() + 1
781 > self.current_index.as_usize() + self.universe_indices.len() =>
783 bug!("Bound vars outside of `self.universe_indices`");
785 ty::Bound(debruijn, bound_ty) if debruijn >= self.current_index => {
786 let universe = self.universe_for(debruijn);
787 let p = ty::PlaceholderType { universe, name: bound_ty.var };
788 self.mapped_types.insert(p, bound_ty);
789 self.infcx.tcx.mk_ty(ty::Placeholder(p))
791 _ if t.has_vars_bound_at_or_above(self.current_index) => t.super_fold_with(self),
796 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
798 ty::ConstKind::Bound(debruijn, _)
799 if debruijn.as_usize() + 1
800 > self.current_index.as_usize() + self.universe_indices.len() =>
802 bug!("Bound vars outside of `self.universe_indices`");
804 ty::ConstKind::Bound(debruijn, bound_const) if debruijn >= self.current_index => {
805 let universe = self.universe_for(debruijn);
806 let p = ty::PlaceholderConst { universe, name: bound_const };
807 self.mapped_consts.insert(p, bound_const);
808 self.infcx.tcx.mk_const(p, ct.ty())
810 _ => ct.super_fold_with(self),
814 fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
815 if p.has_vars_bound_at_or_above(self.current_index) { p.super_fold_with(self) } else { p }
819 /// The inverse of [`BoundVarReplacer`]: replaces placeholders with the bound vars from which they came.
820 pub struct PlaceholderReplacer<'me, 'tcx> {
821 infcx: &'me InferCtxt<'tcx>,
822 mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
823 mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy>,
824 mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
825 universe_indices: &'me [Option<ty::UniverseIndex>],
826 current_index: ty::DebruijnIndex,
829 impl<'me, 'tcx> PlaceholderReplacer<'me, 'tcx> {
830 pub fn replace_placeholders<T: TypeFoldable<'tcx>>(
831 infcx: &'me InferCtxt<'tcx>,
832 mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
833 mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy>,
834 mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
835 universe_indices: &'me [Option<ty::UniverseIndex>],
838 let mut replacer = PlaceholderReplacer {
844 current_index: ty::INNERMOST,
846 value.fold_with(&mut replacer)
850 impl<'tcx> TypeFolder<'tcx> for PlaceholderReplacer<'_, 'tcx> {
851 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
855 fn fold_binder<T: TypeFoldable<'tcx>>(
857 t: ty::Binder<'tcx, T>,
858 ) -> ty::Binder<'tcx, T> {
859 if !t.has_placeholders() && !t.has_infer_regions() {
862 self.current_index.shift_in(1);
863 let t = t.super_fold_with(self);
864 self.current_index.shift_out(1);
868 fn fold_region(&mut self, r0: ty::Region<'tcx>) -> ty::Region<'tcx> {
874 .unwrap_region_constraints()
875 .opportunistic_resolve_region(self.infcx.tcx, r0),
880 ty::RePlaceholder(p) => {
881 let replace_var = self.mapped_regions.get(&p);
883 Some(replace_var) => {
887 .position(|u| matches!(u, Some(pu) if *pu == p.universe))
888 .unwrap_or_else(|| bug!("Unexpected placeholder universe."));
889 let db = ty::DebruijnIndex::from_usize(
890 self.universe_indices.len() - index + self.current_index.as_usize() - 1,
892 self.tcx().mk_region(ty::ReLateBound(db, *replace_var))
900 debug!(?r0, ?r1, ?r2, "fold_region");
905 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
907 ty::Placeholder(p) => {
908 let replace_var = self.mapped_types.get(&p);
910 Some(replace_var) => {
914 .position(|u| matches!(u, Some(pu) if *pu == p.universe))
915 .unwrap_or_else(|| bug!("Unexpected placeholder universe."));
916 let db = ty::DebruijnIndex::from_usize(
917 self.universe_indices.len() - index + self.current_index.as_usize() - 1,
919 self.tcx().mk_ty(ty::Bound(db, *replace_var))
925 _ if ty.has_placeholders() || ty.has_infer_regions() => ty.super_fold_with(self),
930 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
931 if let ty::ConstKind::Placeholder(p) = ct.kind() {
932 let replace_var = self.mapped_consts.get(&p);
934 Some(replace_var) => {
938 .position(|u| matches!(u, Some(pu) if *pu == p.universe))
939 .unwrap_or_else(|| bug!("Unexpected placeholder universe."));
940 let db = ty::DebruijnIndex::from_usize(
941 self.universe_indices.len() - index + self.current_index.as_usize() - 1,
943 self.tcx().mk_const(ty::ConstKind::Bound(db, *replace_var), ct.ty())
948 ct.super_fold_with(self)
953 /// The guts of `normalize`: normalize a specific projection like `<T
954 /// as Trait>::Item`. The result is always a type (and possibly
955 /// additional obligations). If ambiguity arises, which implies that
956 /// there are unresolved type variables in the projection, we will
957 /// substitute a fresh type variable `$X` and generate a new
958 /// obligation `<T as Trait>::Item == $X` for later.
959 pub fn normalize_projection_type<'a, 'b, 'tcx>(
960 selcx: &'a mut SelectionContext<'b, 'tcx>,
961 param_env: ty::ParamEnv<'tcx>,
962 projection_ty: ty::ProjectionTy<'tcx>,
963 cause: ObligationCause<'tcx>,
965 obligations: &mut Vec<PredicateObligation<'tcx>>,
967 opt_normalize_projection_type(
977 .unwrap_or_else(move || {
978 // if we bottom out in ambiguity, create a type variable
979 // and a deferred predicate to resolve this when more type
980 // information is available.
982 selcx.infcx.infer_projection(param_env, projection_ty, cause, depth + 1, obligations).into()
986 /// The guts of `normalize`: normalize a specific projection like `<T
987 /// as Trait>::Item`. The result is always a type (and possibly
988 /// additional obligations). Returns `None` in the case of ambiguity,
989 /// which indicates that there are unbound type variables.
991 /// This function used to return `Option<NormalizedTy<'tcx>>`, which contains a
992 /// `Ty<'tcx>` and an obligations vector. But that obligation vector was very
993 /// often immediately appended to another obligations vector. So now this
994 /// function takes an obligations vector and appends to it directly, which is
995 /// slightly uglier but avoids the need for an extra short-lived allocation.
996 #[instrument(level = "debug", skip(selcx, param_env, cause, obligations))]
997 fn opt_normalize_projection_type<'a, 'b, 'tcx>(
998 selcx: &'a mut SelectionContext<'b, 'tcx>,
999 param_env: ty::ParamEnv<'tcx>,
1000 projection_ty: ty::ProjectionTy<'tcx>,
1001 cause: ObligationCause<'tcx>,
1003 obligations: &mut Vec<PredicateObligation<'tcx>>,
1004 ) -> Result<Option<Term<'tcx>>, InProgress> {
1005 let infcx = selcx.infcx;
1006 // Don't use the projection cache in intercrate mode -
1007 // the `infcx` may be re-used between intercrate in non-intercrate
1008 // mode, which could lead to using incorrect cache results.
1009 let use_cache = !selcx.is_intercrate();
1011 let projection_ty = infcx.resolve_vars_if_possible(projection_ty);
1012 let cache_key = ProjectionCacheKey::new(projection_ty);
1014 // FIXME(#20304) For now, I am caching here, which is good, but it
1015 // means we don't capture the type variables that are created in
1016 // the case of ambiguity. Which means we may create a large stream
1017 // of such variables. OTOH, if we move the caching up a level, we
1018 // would not benefit from caching when proving `T: Trait<U=Foo>`
1019 // bounds. It might be the case that we want two distinct caches,
1020 // or else another kind of cache entry.
1022 let cache_result = if use_cache {
1023 infcx.inner.borrow_mut().projection_cache().try_start(cache_key)
1027 match cache_result {
1028 Ok(()) => debug!("no cache"),
1029 Err(ProjectionCacheEntry::Ambiguous) => {
1030 // If we found ambiguity the last time, that means we will continue
1031 // to do so until some type in the key changes (and we know it
1032 // hasn't, because we just fully resolved it).
1033 debug!("found cache entry: ambiguous");
1036 Err(ProjectionCacheEntry::InProgress) => {
1037 // Under lazy normalization, this can arise when
1038 // bootstrapping. That is, imagine an environment with a
1039 // where-clause like `A::B == u32`. Now, if we are asked
1040 // to normalize `A::B`, we will want to check the
1041 // where-clauses in scope. So we will try to unify `A::B`
1042 // with `A::B`, which can trigger a recursive
1045 debug!("found cache entry: in-progress");
1047 // Cache that normalizing this projection resulted in a cycle. This
1048 // should ensure that, unless this happens within a snapshot that's
1049 // rolled back, fulfillment or evaluation will notice the cycle.
1052 infcx.inner.borrow_mut().projection_cache().recur(cache_key);
1054 return Err(InProgress);
1056 Err(ProjectionCacheEntry::Recur) => {
1057 debug!("recur cache");
1058 return Err(InProgress);
1060 Err(ProjectionCacheEntry::NormalizedTy { ty, complete: _ }) => {
1061 // This is the hottest path in this function.
1063 // If we find the value in the cache, then return it along
1064 // with the obligations that went along with it. Note
1065 // that, when using a fulfillment context, these
1066 // obligations could in principle be ignored: they have
1067 // already been registered when the cache entry was
1068 // created (and hence the new ones will quickly be
1069 // discarded as duplicated). But when doing trait
1070 // evaluation this is not the case, and dropping the trait
1071 // evaluations can causes ICEs (e.g., #43132).
1072 debug!(?ty, "found normalized ty");
1073 obligations.extend(ty.obligations);
1074 return Ok(Some(ty.value));
1076 Err(ProjectionCacheEntry::Error) => {
1077 debug!("opt_normalize_projection_type: found error");
1078 let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth);
1079 obligations.extend(result.obligations);
1080 return Ok(Some(result.value.into()));
1085 Obligation::with_depth(selcx.tcx(), cause.clone(), depth, param_env, projection_ty);
1087 match project(selcx, &obligation) {
1088 Ok(Projected::Progress(Progress {
1089 term: projected_term,
1090 obligations: mut projected_obligations,
1092 // if projection succeeded, then what we get out of this
1093 // is also non-normalized (consider: it was derived from
1094 // an impl, where-clause etc) and hence we must
1097 let projected_term = selcx.infcx.resolve_vars_if_possible(projected_term);
1099 let mut result = if projected_term.has_projections() {
1100 let mut normalizer = AssocTypeNormalizer::new(
1105 &mut projected_obligations,
1107 let normalized_ty = normalizer.fold(projected_term);
1109 Normalized { value: normalized_ty, obligations: projected_obligations }
1111 Normalized { value: projected_term, obligations: projected_obligations }
1114 let mut deduped: SsoHashSet<_> = Default::default();
1115 result.obligations.drain_filter(|projected_obligation| {
1116 if !deduped.insert(projected_obligation.clone()) {
1123 infcx.inner.borrow_mut().projection_cache().insert_term(cache_key, result.clone());
1125 obligations.extend(result.obligations);
1126 Ok(Some(result.value))
1128 Ok(Projected::NoProgress(projected_ty)) => {
1129 let result = Normalized { value: projected_ty, obligations: vec![] };
1131 infcx.inner.borrow_mut().projection_cache().insert_term(cache_key, result.clone());
1133 // No need to extend `obligations`.
1134 Ok(Some(result.value))
1136 Err(ProjectionError::TooManyCandidates) => {
1137 debug!("opt_normalize_projection_type: too many candidates");
1139 infcx.inner.borrow_mut().projection_cache().ambiguous(cache_key);
1143 Err(ProjectionError::TraitSelectionError(_)) => {
1144 debug!("opt_normalize_projection_type: ERROR");
1145 // if we got an error processing the `T as Trait` part,
1146 // just return `ty::err` but add the obligation `T :
1147 // Trait`, which when processed will cause the error to be
1151 infcx.inner.borrow_mut().projection_cache().error(cache_key);
1153 let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth);
1154 obligations.extend(result.obligations);
1155 Ok(Some(result.value.into()))
1160 /// If we are projecting `<T as Trait>::Item`, but `T: Trait` does not
1161 /// hold. In various error cases, we cannot generate a valid
1162 /// normalized projection. Therefore, we create an inference variable
1163 /// return an associated obligation that, when fulfilled, will lead to
1166 /// Note that we used to return `Error` here, but that was quite
1167 /// dubious -- the premise was that an error would *eventually* be
1168 /// reported, when the obligation was processed. But in general once
1169 /// you see an `Error` you are supposed to be able to assume that an
1170 /// error *has been* reported, so that you can take whatever heuristic
1171 /// paths you want to take. To make things worse, it was possible for
1172 /// cycles to arise, where you basically had a setup like `<MyType<$0>
1173 /// as Trait>::Foo == $0`. Here, normalizing `<MyType<$0> as
1174 /// Trait>::Foo> to `[type error]` would lead to an obligation of
1175 /// `<MyType<[type error]> as Trait>::Foo`. We are supposed to report
1176 /// an error for this obligation, but we legitimately should not,
1177 /// because it contains `[type error]`. Yuck! (See issue #29857 for
1178 /// one case where this arose.)
1179 fn normalize_to_error<'a, 'tcx>(
1180 selcx: &mut SelectionContext<'a, 'tcx>,
1181 param_env: ty::ParamEnv<'tcx>,
1182 projection_ty: ty::ProjectionTy<'tcx>,
1183 cause: ObligationCause<'tcx>,
1185 ) -> NormalizedTy<'tcx> {
1186 let trait_ref = ty::Binder::dummy(projection_ty.trait_ref(selcx.tcx()));
1187 let trait_obligation = Obligation {
1189 recursion_depth: depth,
1191 predicate: trait_ref.without_const().to_predicate(selcx.tcx()),
1193 let tcx = selcx.infcx.tcx;
1194 let def_id = projection_ty.item_def_id;
1195 let new_value = selcx.infcx.next_ty_var(TypeVariableOrigin {
1196 kind: TypeVariableOriginKind::NormalizeProjectionType,
1197 span: tcx.def_span(def_id),
1199 Normalized { value: new_value, obligations: vec![trait_obligation] }
1202 enum Projected<'tcx> {
1203 Progress(Progress<'tcx>),
1204 NoProgress(ty::Term<'tcx>),
1207 struct Progress<'tcx> {
1208 term: ty::Term<'tcx>,
1209 obligations: Vec<PredicateObligation<'tcx>>,
1212 impl<'tcx> Progress<'tcx> {
1213 fn error(tcx: TyCtxt<'tcx>) -> Self {
1214 Progress { term: tcx.ty_error().into(), obligations: vec![] }
1217 fn with_addl_obligations(mut self, mut obligations: Vec<PredicateObligation<'tcx>>) -> Self {
1218 self.obligations.append(&mut obligations);
1223 /// Computes the result of a projection type (if we can).
1226 /// - `obligation` must be fully normalized
1227 #[instrument(level = "info", skip(selcx))]
1228 fn project<'cx, 'tcx>(
1229 selcx: &mut SelectionContext<'cx, 'tcx>,
1230 obligation: &ProjectionTyObligation<'tcx>,
1231 ) -> Result<Projected<'tcx>, ProjectionError<'tcx>> {
1232 if !selcx.tcx().recursion_limit().value_within_limit(obligation.recursion_depth) {
1233 // This should really be an immediate error, but some existing code
1234 // relies on being able to recover from this.
1235 return Err(ProjectionError::TraitSelectionError(SelectionError::Overflow(
1236 OverflowError::Canonical,
1240 if obligation.predicate.references_error() {
1241 return Ok(Projected::Progress(Progress::error(selcx.tcx())));
1244 let mut candidates = ProjectionCandidateSet::None;
1246 assemble_candidate_for_impl_trait_in_trait(selcx, obligation, &mut candidates);
1248 // Make sure that the following procedures are kept in order. ParamEnv
1249 // needs to be first because it has highest priority, and Select checks
1250 // the return value of push_candidate which assumes it's ran at last.
1251 assemble_candidates_from_param_env(selcx, obligation, &mut candidates);
1253 assemble_candidates_from_trait_def(selcx, obligation, &mut candidates);
1255 assemble_candidates_from_object_ty(selcx, obligation, &mut candidates);
1257 if let ProjectionCandidateSet::Single(ProjectionCandidate::Object(_)) = candidates {
1258 // Avoid normalization cycle from selection (see
1259 // `assemble_candidates_from_object_ty`).
1260 // FIXME(lazy_normalization): Lazy normalization should save us from
1261 // having to special case this.
1263 assemble_candidates_from_impls(selcx, obligation, &mut candidates);
1267 ProjectionCandidateSet::Single(candidate) => {
1268 Ok(Projected::Progress(confirm_candidate(selcx, obligation, candidate)))
1270 ProjectionCandidateSet::None => Ok(Projected::NoProgress(
1271 // FIXME(associated_const_generics): this may need to change in the future?
1272 // need to investigate whether or not this is fine.
1275 .mk_projection(obligation.predicate.item_def_id, obligation.predicate.substs)
1278 // Error occurred while trying to processing impls.
1279 ProjectionCandidateSet::Error(e) => Err(ProjectionError::TraitSelectionError(e)),
1280 // Inherent ambiguity that prevents us from even enumerating the
1282 ProjectionCandidateSet::Ambiguous => Err(ProjectionError::TooManyCandidates),
1286 /// If the predicate's item is an `ImplTraitPlaceholder`, we do a select on the
1287 /// corresponding trait ref. If this yields an `impl`, then we're able to project
1288 /// to a concrete type, since we have an `impl`'s method to provide the RPITIT.
1289 fn assemble_candidate_for_impl_trait_in_trait<'cx, 'tcx>(
1290 selcx: &mut SelectionContext<'cx, 'tcx>,
1291 obligation: &ProjectionTyObligation<'tcx>,
1292 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1294 let tcx = selcx.tcx();
1295 if tcx.def_kind(obligation.predicate.item_def_id) == DefKind::ImplTraitPlaceholder {
1296 let trait_fn_def_id = tcx.impl_trait_in_trait_parent(obligation.predicate.item_def_id);
1297 // If we are trying to project an RPITIT with trait's default `Self` parameter,
1298 // then we must be within a default trait body.
1299 if obligation.predicate.self_ty()
1300 == ty::InternalSubsts::identity_for_item(tcx, obligation.predicate.item_def_id)
1302 && tcx.associated_item(trait_fn_def_id).defaultness(tcx).has_value()
1304 candidate_set.push_candidate(ProjectionCandidate::ImplTraitInTrait(
1305 ImplTraitInTraitCandidate::Trait,
1310 let trait_def_id = tcx.parent(trait_fn_def_id);
1312 obligation.predicate.substs.truncate_to(tcx, tcx.generics_of(trait_def_id));
1313 // FIXME(named-returns): Binders
1314 let trait_predicate =
1315 ty::Binder::dummy(ty::TraitRef { def_id: trait_def_id, substs: trait_substs });
1317 let _ = selcx.infcx.commit_if_ok(|_| {
1318 match selcx.select(&obligation.with(tcx, trait_predicate)) {
1319 Ok(Some(super::ImplSource::UserDefined(data))) => {
1320 candidate_set.push_candidate(ProjectionCandidate::ImplTraitInTrait(
1321 ImplTraitInTraitCandidate::Impl(data),
1326 candidate_set.mark_ambiguous();
1330 // Don't know enough about the impl to provide a useful signature
1334 debug!(error = ?e, "selection error");
1335 candidate_set.mark_error(e);
1343 /// The first thing we have to do is scan through the parameter
1344 /// environment to see whether there are any projection predicates
1345 /// there that can answer this question.
1346 fn assemble_candidates_from_param_env<'cx, 'tcx>(
1347 selcx: &mut SelectionContext<'cx, 'tcx>,
1348 obligation: &ProjectionTyObligation<'tcx>,
1349 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1351 assemble_candidates_from_predicates(
1355 ProjectionCandidate::ParamEnv,
1356 obligation.param_env.caller_bounds().iter(),
1361 /// In the case of a nested projection like `<<A as Foo>::FooT as Bar>::BarT`, we may find
1362 /// that the definition of `Foo` has some clues:
1364 /// ```ignore (illustrative)
1366 /// type FooT : Bar<BarT=i32>
1370 /// Here, for example, we could conclude that the result is `i32`.
1371 fn assemble_candidates_from_trait_def<'cx, 'tcx>(
1372 selcx: &mut SelectionContext<'cx, 'tcx>,
1373 obligation: &ProjectionTyObligation<'tcx>,
1374 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1376 debug!("assemble_candidates_from_trait_def(..)");
1378 let tcx = selcx.tcx();
1379 // Check whether the self-type is itself a projection.
1380 // If so, extract what we know from the trait and try to come up with a good answer.
1381 let bounds = match *obligation.predicate.self_ty().kind() {
1382 ty::Projection(ref data) => tcx.bound_item_bounds(data.item_def_id).subst(tcx, data.substs),
1383 ty::Opaque(def_id, substs) => tcx.bound_item_bounds(def_id).subst(tcx, substs),
1384 ty::Infer(ty::TyVar(_)) => {
1385 // If the self-type is an inference variable, then it MAY wind up
1386 // being a projected type, so induce an ambiguity.
1387 candidate_set.mark_ambiguous();
1393 assemble_candidates_from_predicates(
1397 ProjectionCandidate::TraitDef,
1403 /// In the case of a trait object like
1404 /// `<dyn Iterator<Item = ()> as Iterator>::Item` we can use the existential
1405 /// predicate in the trait object.
1407 /// We don't go through the select candidate for these bounds to avoid cycles:
1408 /// In the above case, `dyn Iterator<Item = ()>: Iterator` would create a
1409 /// nested obligation of `<dyn Iterator<Item = ()> as Iterator>::Item: Sized`,
1410 /// this then has to be normalized without having to prove
1411 /// `dyn Iterator<Item = ()>: Iterator` again.
1412 fn assemble_candidates_from_object_ty<'cx, 'tcx>(
1413 selcx: &mut SelectionContext<'cx, 'tcx>,
1414 obligation: &ProjectionTyObligation<'tcx>,
1415 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1417 debug!("assemble_candidates_from_object_ty(..)");
1419 let tcx = selcx.tcx();
1421 let self_ty = obligation.predicate.self_ty();
1422 let object_ty = selcx.infcx.shallow_resolve(self_ty);
1423 let data = match object_ty.kind() {
1424 ty::Dynamic(data, ..) => data,
1425 ty::Infer(ty::TyVar(_)) => {
1426 // If the self-type is an inference variable, then it MAY wind up
1427 // being an object type, so induce an ambiguity.
1428 candidate_set.mark_ambiguous();
1433 let env_predicates = data
1434 .projection_bounds()
1435 .filter(|bound| bound.item_def_id() == obligation.predicate.item_def_id)
1436 .map(|p| p.with_self_ty(tcx, object_ty).to_predicate(tcx));
1438 assemble_candidates_from_predicates(
1442 ProjectionCandidate::Object,
1450 skip(selcx, candidate_set, ctor, env_predicates, potentially_unnormalized_candidates)
1452 fn assemble_candidates_from_predicates<'cx, 'tcx>(
1453 selcx: &mut SelectionContext<'cx, 'tcx>,
1454 obligation: &ProjectionTyObligation<'tcx>,
1455 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1456 ctor: fn(ty::PolyProjectionPredicate<'tcx>) -> ProjectionCandidate<'tcx>,
1457 env_predicates: impl Iterator<Item = ty::Predicate<'tcx>>,
1458 potentially_unnormalized_candidates: bool,
1460 let infcx = selcx.infcx;
1461 for predicate in env_predicates {
1462 let bound_predicate = predicate.kind();
1463 if let ty::PredicateKind::Clause(ty::Clause::Projection(data)) =
1464 predicate.kind().skip_binder()
1466 let data = bound_predicate.rebind(data);
1467 if data.projection_def_id() != obligation.predicate.item_def_id {
1471 let is_match = infcx.probe(|_| {
1472 selcx.match_projection_projections(
1475 potentially_unnormalized_candidates,
1480 ProjectionMatchesProjection::Yes => {
1481 candidate_set.push_candidate(ctor(data));
1483 if potentially_unnormalized_candidates
1484 && !obligation.predicate.has_non_region_infer()
1486 // HACK: Pick the first trait def candidate for a fully
1487 // inferred predicate. This is to allow duplicates that
1488 // differ only in normalization.
1492 ProjectionMatchesProjection::Ambiguous => {
1493 candidate_set.mark_ambiguous();
1495 ProjectionMatchesProjection::No => {}
1501 #[instrument(level = "debug", skip(selcx, obligation, candidate_set))]
1502 fn assemble_candidates_from_impls<'cx, 'tcx>(
1503 selcx: &mut SelectionContext<'cx, 'tcx>,
1504 obligation: &ProjectionTyObligation<'tcx>,
1505 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1507 // Can't assemble candidate from impl for RPITIT
1508 if selcx.tcx().def_kind(obligation.predicate.item_def_id) == DefKind::ImplTraitPlaceholder {
1512 // If we are resolving `<T as TraitRef<...>>::Item == Type`,
1513 // start out by selecting the predicate `T as TraitRef<...>`:
1514 let poly_trait_ref = ty::Binder::dummy(obligation.predicate.trait_ref(selcx.tcx()));
1515 let trait_obligation = obligation.with(selcx.tcx(), poly_trait_ref);
1516 let _ = selcx.infcx.commit_if_ok(|_| {
1517 let impl_source = match selcx.select(&trait_obligation) {
1518 Ok(Some(impl_source)) => impl_source,
1520 candidate_set.mark_ambiguous();
1524 debug!(error = ?e, "selection error");
1525 candidate_set.mark_error(e);
1530 let eligible = match &impl_source {
1531 super::ImplSource::Closure(_)
1532 | super::ImplSource::Generator(_)
1533 | super::ImplSource::Future(_)
1534 | super::ImplSource::FnPointer(_)
1535 | super::ImplSource::TraitAlias(_) => true,
1536 super::ImplSource::UserDefined(impl_data) => {
1537 // We have to be careful when projecting out of an
1538 // impl because of specialization. If we are not in
1539 // codegen (i.e., projection mode is not "any"), and the
1540 // impl's type is declared as default, then we disable
1541 // projection (even if the trait ref is fully
1542 // monomorphic). In the case where trait ref is not
1543 // fully monomorphic (i.e., includes type parameters),
1544 // this is because those type parameters may
1545 // ultimately be bound to types from other crates that
1546 // may have specialized impls we can't see. In the
1547 // case where the trait ref IS fully monomorphic, this
1548 // is a policy decision that we made in the RFC in
1549 // order to preserve flexibility for the crate that
1550 // defined the specializable impl to specialize later
1551 // for existing types.
1553 // In either case, we handle this by not adding a
1554 // candidate for an impl if it contains a `default`
1557 // NOTE: This should be kept in sync with the similar code in
1558 // `rustc_ty_utils::instance::resolve_associated_item()`.
1560 assoc_def(selcx, impl_data.impl_def_id, obligation.predicate.item_def_id)
1561 .map_err(|ErrorGuaranteed { .. }| ())?;
1563 if node_item.is_final() {
1564 // Non-specializable items are always projectable.
1567 // Only reveal a specializable default if we're past type-checking
1568 // and the obligation is monomorphic, otherwise passes such as
1569 // transmute checking and polymorphic MIR optimizations could
1570 // get a result which isn't correct for all monomorphizations.
1571 if obligation.param_env.reveal() == Reveal::All {
1572 // NOTE(eddyb) inference variables can resolve to parameters, so
1573 // assume `poly_trait_ref` isn't monomorphic, if it contains any.
1574 let poly_trait_ref = selcx.infcx.resolve_vars_if_possible(poly_trait_ref);
1575 !poly_trait_ref.still_further_specializable()
1578 assoc_ty = ?selcx.tcx().def_path_str(node_item.item.def_id),
1579 ?obligation.predicate,
1580 "assemble_candidates_from_impls: not eligible due to default",
1586 super::ImplSource::Builtin(..) => {
1587 // While a builtin impl may be known to exist, the associated type may not yet
1588 // be known. Any type with multiple potential associated types is therefore
1590 let self_ty = selcx.infcx.shallow_resolve(obligation.predicate.self_ty());
1592 let lang_items = selcx.tcx().lang_items();
1593 if lang_items.discriminant_kind_trait() == Some(poly_trait_ref.def_id()) {
1594 match self_ty.kind() {
1612 | ty::GeneratorWitness(..)
1615 // Integers and floats always have `u8` as their discriminant.
1616 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(..)) => true,
1618 // type parameters, opaques, and unnormalized projections have pointer
1619 // metadata if they're known (e.g. by the param_env) to be sized
1621 | ty::Projection(..)
1624 | ty::Placeholder(..)
1626 | ty::Error(_) => false,
1628 } else if lang_items.pointee_trait() == Some(poly_trait_ref.def_id()) {
1629 let tail = selcx.tcx().struct_tail_with_normalize(
1632 // We throw away any obligations we get from this, since we normalize
1633 // and confirm these obligations once again during confirmation
1634 normalize_with_depth(
1636 obligation.param_env,
1637 obligation.cause.clone(),
1638 obligation.recursion_depth + 1,
1662 | ty::GeneratorWitness(..)
1664 // Extern types have unit metadata, according to RFC 2850
1666 // If returned by `struct_tail_without_normalization` this is a unit struct
1667 // without any fields, or not a struct, and therefore is Sized.
1669 // If returned by `struct_tail_without_normalization` this is the empty tuple.
1671 // Integers and floats are always Sized, and so have unit type metadata.
1672 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(..)) => true,
1674 // type parameters, opaques, and unnormalized projections have pointer
1675 // metadata if they're known (e.g. by the param_env) to be sized
1676 ty::Param(_) | ty::Projection(..) | ty::Opaque(..)
1677 if selcx.infcx.predicate_must_hold_modulo_regions(
1681 selcx.tcx().at(obligation.cause.span()).mk_trait_ref(LangItem::Sized, [self_ty]),
1690 // FIXME(compiler-errors): are Bound and Placeholder types ever known sized?
1692 | ty::Projection(..)
1695 | ty::Placeholder(..)
1698 if tail.has_infer_types() {
1699 candidate_set.mark_ambiguous();
1705 bug!("unexpected builtin trait with associated type: {poly_trait_ref:?}")
1708 super::ImplSource::Param(..) => {
1709 // This case tell us nothing about the value of an
1710 // associated type. Consider:
1713 // trait SomeTrait { type Foo; }
1714 // fn foo<T:SomeTrait>(...) { }
1717 // If the user writes `<T as SomeTrait>::Foo`, then the `T
1718 // : SomeTrait` binding does not help us decide what the
1719 // type `Foo` is (at least, not more specifically than
1720 // what we already knew).
1722 // But wait, you say! What about an example like this:
1725 // fn bar<T:SomeTrait<Foo=usize>>(...) { ... }
1728 // Doesn't the `T : SomeTrait<Foo=usize>` predicate help
1729 // resolve `T::Foo`? And of course it does, but in fact
1730 // that single predicate is desugared into two predicates
1731 // in the compiler: a trait predicate (`T : SomeTrait`) and a
1732 // projection. And the projection where clause is handled
1733 // in `assemble_candidates_from_param_env`.
1736 super::ImplSource::Object(_) => {
1737 // Handled by the `Object` projection candidate. See
1738 // `assemble_candidates_from_object_ty` for an explanation of
1739 // why we special case object types.
1742 super::ImplSource::AutoImpl(..)
1743 | super::ImplSource::TraitUpcasting(_)
1744 | super::ImplSource::ConstDestruct(_) => {
1745 // These traits have no associated types.
1746 selcx.tcx().sess.delay_span_bug(
1747 obligation.cause.span,
1748 &format!("Cannot project an associated type from `{:?}`", impl_source),
1755 if candidate_set.push_candidate(ProjectionCandidate::Select(impl_source)) {
1766 fn confirm_candidate<'cx, 'tcx>(
1767 selcx: &mut SelectionContext<'cx, 'tcx>,
1768 obligation: &ProjectionTyObligation<'tcx>,
1769 candidate: ProjectionCandidate<'tcx>,
1770 ) -> Progress<'tcx> {
1771 debug!(?obligation, ?candidate, "confirm_candidate");
1772 let mut progress = match candidate {
1773 ProjectionCandidate::ParamEnv(poly_projection)
1774 | ProjectionCandidate::Object(poly_projection) => {
1775 confirm_param_env_candidate(selcx, obligation, poly_projection, false)
1778 ProjectionCandidate::TraitDef(poly_projection) => {
1779 confirm_param_env_candidate(selcx, obligation, poly_projection, true)
1782 ProjectionCandidate::Select(impl_source) => {
1783 confirm_select_candidate(selcx, obligation, impl_source)
1785 ProjectionCandidate::ImplTraitInTrait(ImplTraitInTraitCandidate::Impl(data)) => {
1786 confirm_impl_trait_in_trait_candidate(selcx, obligation, data)
1788 // If we're projecting an RPITIT for a default trait body, that's just
1789 // the same def-id, but as an opaque type (with regular RPIT semantics).
1790 ProjectionCandidate::ImplTraitInTrait(ImplTraitInTraitCandidate::Trait) => Progress {
1793 .mk_opaque(obligation.predicate.item_def_id, obligation.predicate.substs)
1795 obligations: vec![],
1799 // When checking for cycle during evaluation, we compare predicates with
1800 // "syntactic" equality. Since normalization generally introduces a type
1801 // with new region variables, we need to resolve them to existing variables
1802 // when possible for this to work. See `auto-trait-projection-recursion.rs`
1803 // for a case where this matters.
1804 if progress.term.has_infer_regions() {
1805 progress.term = progress.term.fold_with(&mut OpportunisticRegionResolver::new(selcx.infcx));
1810 fn confirm_select_candidate<'cx, 'tcx>(
1811 selcx: &mut SelectionContext<'cx, 'tcx>,
1812 obligation: &ProjectionTyObligation<'tcx>,
1813 impl_source: Selection<'tcx>,
1814 ) -> Progress<'tcx> {
1816 super::ImplSource::UserDefined(data) => confirm_impl_candidate(selcx, obligation, data),
1817 super::ImplSource::Generator(data) => confirm_generator_candidate(selcx, obligation, data),
1818 super::ImplSource::Future(data) => confirm_future_candidate(selcx, obligation, data),
1819 super::ImplSource::Closure(data) => confirm_closure_candidate(selcx, obligation, data),
1820 super::ImplSource::FnPointer(data) => confirm_fn_pointer_candidate(selcx, obligation, data),
1821 super::ImplSource::Builtin(data) => confirm_builtin_candidate(selcx, obligation, data),
1822 super::ImplSource::Object(_)
1823 | super::ImplSource::AutoImpl(..)
1824 | super::ImplSource::Param(..)
1825 | super::ImplSource::TraitUpcasting(_)
1826 | super::ImplSource::TraitAlias(..)
1827 | super::ImplSource::ConstDestruct(_) => {
1828 // we don't create Select candidates with this kind of resolution
1830 obligation.cause.span,
1831 "Cannot project an associated type from `{:?}`",
1838 fn confirm_generator_candidate<'cx, 'tcx>(
1839 selcx: &mut SelectionContext<'cx, 'tcx>,
1840 obligation: &ProjectionTyObligation<'tcx>,
1841 impl_source: ImplSourceGeneratorData<'tcx, PredicateObligation<'tcx>>,
1842 ) -> Progress<'tcx> {
1843 let gen_sig = impl_source.substs.as_generator().poly_sig();
1844 let Normalized { value: gen_sig, obligations } = normalize_with_depth(
1846 obligation.param_env,
1847 obligation.cause.clone(),
1848 obligation.recursion_depth + 1,
1852 debug!(?obligation, ?gen_sig, ?obligations, "confirm_generator_candidate");
1854 let tcx = selcx.tcx();
1856 let gen_def_id = tcx.require_lang_item(LangItem::Generator, None);
1858 let predicate = super::util::generator_trait_ref_and_outputs(
1861 obligation.predicate.self_ty(),
1864 .map_bound(|(trait_ref, yield_ty, return_ty)| {
1865 let name = tcx.associated_item(obligation.predicate.item_def_id).name;
1866 let ty = if name == sym::Return {
1868 } else if name == sym::Yield {
1874 ty::ProjectionPredicate {
1875 projection_ty: ty::ProjectionTy {
1876 substs: trait_ref.substs,
1877 item_def_id: obligation.predicate.item_def_id,
1883 confirm_param_env_candidate(selcx, obligation, predicate, false)
1884 .with_addl_obligations(impl_source.nested)
1885 .with_addl_obligations(obligations)
1888 fn confirm_future_candidate<'cx, 'tcx>(
1889 selcx: &mut SelectionContext<'cx, 'tcx>,
1890 obligation: &ProjectionTyObligation<'tcx>,
1891 impl_source: ImplSourceFutureData<'tcx, PredicateObligation<'tcx>>,
1892 ) -> Progress<'tcx> {
1893 let gen_sig = impl_source.substs.as_generator().poly_sig();
1894 let Normalized { value: gen_sig, obligations } = normalize_with_depth(
1896 obligation.param_env,
1897 obligation.cause.clone(),
1898 obligation.recursion_depth + 1,
1902 debug!(?obligation, ?gen_sig, ?obligations, "confirm_future_candidate");
1904 let tcx = selcx.tcx();
1905 let fut_def_id = tcx.require_lang_item(LangItem::Future, None);
1907 let predicate = super::util::future_trait_ref_and_outputs(
1910 obligation.predicate.self_ty(),
1913 .map_bound(|(trait_ref, return_ty)| {
1914 debug_assert_eq!(tcx.associated_item(obligation.predicate.item_def_id).name, sym::Output);
1916 ty::ProjectionPredicate {
1917 projection_ty: ty::ProjectionTy {
1918 substs: trait_ref.substs,
1919 item_def_id: obligation.predicate.item_def_id,
1921 term: return_ty.into(),
1925 confirm_param_env_candidate(selcx, obligation, predicate, false)
1926 .with_addl_obligations(impl_source.nested)
1927 .with_addl_obligations(obligations)
1930 fn confirm_builtin_candidate<'cx, 'tcx>(
1931 selcx: &mut SelectionContext<'cx, 'tcx>,
1932 obligation: &ProjectionTyObligation<'tcx>,
1933 data: ImplSourceBuiltinData<PredicateObligation<'tcx>>,
1934 ) -> Progress<'tcx> {
1935 let tcx = selcx.tcx();
1936 let self_ty = obligation.predicate.self_ty();
1937 let substs = tcx.mk_substs([self_ty.into()].iter());
1938 let lang_items = tcx.lang_items();
1939 let item_def_id = obligation.predicate.item_def_id;
1940 let trait_def_id = tcx.trait_of_item(item_def_id).unwrap();
1941 let (term, obligations) = if lang_items.discriminant_kind_trait() == Some(trait_def_id) {
1942 let discriminant_def_id = tcx.require_lang_item(LangItem::Discriminant, None);
1943 assert_eq!(discriminant_def_id, item_def_id);
1945 (self_ty.discriminant_ty(tcx).into(), Vec::new())
1946 } else if lang_items.pointee_trait() == Some(trait_def_id) {
1947 let metadata_def_id = tcx.require_lang_item(LangItem::Metadata, None);
1948 assert_eq!(metadata_def_id, item_def_id);
1950 let mut obligations = Vec::new();
1951 let (metadata_ty, check_is_sized) = self_ty.ptr_metadata_ty(tcx, |ty| {
1952 normalize_with_depth_to(
1954 obligation.param_env,
1955 obligation.cause.clone(),
1956 obligation.recursion_depth + 1,
1962 let sized_predicate = ty::Binder::dummy(
1963 tcx.at(obligation.cause.span()).mk_trait_ref(LangItem::Sized, [self_ty]),
1966 obligations.push(obligation.with(tcx, sized_predicate));
1968 (metadata_ty.into(), obligations)
1970 bug!("unexpected builtin trait with associated type: {:?}", obligation.predicate);
1974 ty::ProjectionPredicate { projection_ty: ty::ProjectionTy { substs, item_def_id }, term };
1976 confirm_param_env_candidate(selcx, obligation, ty::Binder::dummy(predicate), false)
1977 .with_addl_obligations(obligations)
1978 .with_addl_obligations(data.nested)
1981 fn confirm_fn_pointer_candidate<'cx, 'tcx>(
1982 selcx: &mut SelectionContext<'cx, 'tcx>,
1983 obligation: &ProjectionTyObligation<'tcx>,
1984 fn_pointer_impl_source: ImplSourceFnPointerData<'tcx, PredicateObligation<'tcx>>,
1985 ) -> Progress<'tcx> {
1986 let fn_type = selcx.infcx.shallow_resolve(fn_pointer_impl_source.fn_ty);
1987 let sig = fn_type.fn_sig(selcx.tcx());
1988 let Normalized { value: sig, obligations } = normalize_with_depth(
1990 obligation.param_env,
1991 obligation.cause.clone(),
1992 obligation.recursion_depth + 1,
1996 confirm_callable_candidate(selcx, obligation, sig, util::TupleArgumentsFlag::Yes)
1997 .with_addl_obligations(fn_pointer_impl_source.nested)
1998 .with_addl_obligations(obligations)
2001 fn confirm_closure_candidate<'cx, 'tcx>(
2002 selcx: &mut SelectionContext<'cx, 'tcx>,
2003 obligation: &ProjectionTyObligation<'tcx>,
2004 impl_source: ImplSourceClosureData<'tcx, PredicateObligation<'tcx>>,
2005 ) -> Progress<'tcx> {
2006 let closure_sig = impl_source.substs.as_closure().sig();
2007 let Normalized { value: closure_sig, obligations } = normalize_with_depth(
2009 obligation.param_env,
2010 obligation.cause.clone(),
2011 obligation.recursion_depth + 1,
2015 debug!(?obligation, ?closure_sig, ?obligations, "confirm_closure_candidate");
2017 confirm_callable_candidate(selcx, obligation, closure_sig, util::TupleArgumentsFlag::No)
2018 .with_addl_obligations(impl_source.nested)
2019 .with_addl_obligations(obligations)
2022 fn confirm_callable_candidate<'cx, 'tcx>(
2023 selcx: &mut SelectionContext<'cx, 'tcx>,
2024 obligation: &ProjectionTyObligation<'tcx>,
2025 fn_sig: ty::PolyFnSig<'tcx>,
2026 flag: util::TupleArgumentsFlag,
2027 ) -> Progress<'tcx> {
2028 let tcx = selcx.tcx();
2030 debug!(?obligation, ?fn_sig, "confirm_callable_candidate");
2032 let fn_once_def_id = tcx.require_lang_item(LangItem::FnOnce, None);
2033 let fn_once_output_def_id = tcx.require_lang_item(LangItem::FnOnceOutput, None);
2035 let predicate = super::util::closure_trait_ref_and_return_type(
2038 obligation.predicate.self_ty(),
2042 .map_bound(|(trait_ref, ret_type)| ty::ProjectionPredicate {
2043 projection_ty: ty::ProjectionTy {
2044 substs: trait_ref.substs,
2045 item_def_id: fn_once_output_def_id,
2047 term: ret_type.into(),
2050 confirm_param_env_candidate(selcx, obligation, predicate, true)
2053 fn confirm_param_env_candidate<'cx, 'tcx>(
2054 selcx: &mut SelectionContext<'cx, 'tcx>,
2055 obligation: &ProjectionTyObligation<'tcx>,
2056 poly_cache_entry: ty::PolyProjectionPredicate<'tcx>,
2057 potentially_unnormalized_candidate: bool,
2058 ) -> Progress<'tcx> {
2059 let infcx = selcx.infcx;
2060 let cause = &obligation.cause;
2061 let param_env = obligation.param_env;
2063 let cache_entry = infcx.replace_bound_vars_with_fresh_vars(
2065 LateBoundRegionConversionTime::HigherRankedType,
2069 let cache_projection = cache_entry.projection_ty;
2070 let mut nested_obligations = Vec::new();
2071 let obligation_projection = obligation.predicate;
2072 let obligation_projection = ensure_sufficient_stack(|| {
2073 normalize_with_depth_to(
2075 obligation.param_env,
2076 obligation.cause.clone(),
2077 obligation.recursion_depth + 1,
2078 obligation_projection,
2079 &mut nested_obligations,
2082 let cache_projection = if potentially_unnormalized_candidate {
2083 ensure_sufficient_stack(|| {
2084 normalize_with_depth_to(
2086 obligation.param_env,
2087 obligation.cause.clone(),
2088 obligation.recursion_depth + 1,
2090 &mut nested_obligations,
2097 debug!(?cache_projection, ?obligation_projection);
2099 match infcx.at(cause, param_env).eq(cache_projection, obligation_projection) {
2100 Ok(InferOk { value: _, obligations }) => {
2101 nested_obligations.extend(obligations);
2102 assoc_ty_own_obligations(selcx, obligation, &mut nested_obligations);
2103 // FIXME(associated_const_equality): Handle consts here as well? Maybe this progress type should just take
2105 Progress { term: cache_entry.term, obligations: nested_obligations }
2109 "Failed to unify obligation `{:?}` with poly_projection `{:?}`: {:?}",
2110 obligation, poly_cache_entry, e,
2112 debug!("confirm_param_env_candidate: {}", msg);
2113 let err = infcx.tcx.ty_error_with_message(obligation.cause.span, &msg);
2114 Progress { term: err.into(), obligations: vec![] }
2119 fn confirm_impl_candidate<'cx, 'tcx>(
2120 selcx: &mut SelectionContext<'cx, 'tcx>,
2121 obligation: &ProjectionTyObligation<'tcx>,
2122 impl_impl_source: ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>>,
2123 ) -> Progress<'tcx> {
2124 let tcx = selcx.tcx();
2126 let ImplSourceUserDefinedData { impl_def_id, substs, mut nested } = impl_impl_source;
2127 let assoc_item_id = obligation.predicate.item_def_id;
2128 let trait_def_id = tcx.trait_id_of_impl(impl_def_id).unwrap();
2130 let param_env = obligation.param_env;
2131 let Ok(assoc_ty) = assoc_def(selcx, impl_def_id, assoc_item_id) else {
2132 return Progress { term: tcx.ty_error().into(), obligations: nested };
2135 if !assoc_ty.item.defaultness(tcx).has_value() {
2136 // This means that the impl is missing a definition for the
2137 // associated type. This error will be reported by the type
2138 // checker method `check_impl_items_against_trait`, so here we
2139 // just return Error.
2141 "confirm_impl_candidate: no associated type {:?} for {:?}",
2142 assoc_ty.item.name, obligation.predicate
2144 return Progress { term: tcx.ty_error().into(), obligations: nested };
2146 // If we're trying to normalize `<Vec<u32> as X>::A<S>` using
2147 //`impl<T> X for Vec<T> { type A<Y> = Box<Y>; }`, then:
2149 // * `obligation.predicate.substs` is `[Vec<u32>, S]`
2150 // * `substs` is `[u32]`
2151 // * `substs` ends up as `[u32, S]`
2152 let substs = obligation.predicate.substs.rebase_onto(tcx, trait_def_id, substs);
2154 translate_substs(selcx.infcx, param_env, impl_def_id, substs, assoc_ty.defining_node);
2155 let ty = tcx.bound_type_of(assoc_ty.item.def_id);
2156 let is_const = matches!(tcx.def_kind(assoc_ty.item.def_id), DefKind::AssocConst);
2157 let term: ty::EarlyBinder<ty::Term<'tcx>> = if is_const {
2158 let identity_substs =
2159 crate::traits::InternalSubsts::identity_for_item(tcx, assoc_ty.item.def_id);
2160 let did = ty::WithOptConstParam::unknown(assoc_ty.item.def_id);
2161 let kind = ty::ConstKind::Unevaluated(ty::UnevaluatedConst::new(did, identity_substs));
2162 ty.map_bound(|ty| tcx.mk_const(kind, ty).into())
2164 ty.map_bound(|ty| ty.into())
2166 if !check_substs_compatible(tcx, &assoc_ty.item, substs) {
2167 let err = tcx.ty_error_with_message(
2168 obligation.cause.span,
2169 "impl item and trait item have different parameters",
2171 Progress { term: err.into(), obligations: nested }
2173 assoc_ty_own_obligations(selcx, obligation, &mut nested);
2174 Progress { term: term.subst(tcx, substs), obligations: nested }
2178 // Verify that the trait item and its implementation have compatible substs lists
2179 fn check_substs_compatible<'tcx>(
2181 assoc_item: &ty::AssocItem,
2182 substs: ty::SubstsRef<'tcx>,
2184 fn check_substs_compatible_inner<'tcx>(
2186 generics: &'tcx ty::Generics,
2187 args: &'tcx [ty::GenericArg<'tcx>],
2189 if generics.count() != args.len() {
2193 let (parent_args, own_args) = args.split_at(generics.parent_count);
2195 if let Some(parent) = generics.parent
2196 && let parent_generics = tcx.generics_of(parent)
2197 && !check_substs_compatible_inner(tcx, parent_generics, parent_args) {
2201 for (param, arg) in std::iter::zip(&generics.params, own_args) {
2202 match (¶m.kind, arg.unpack()) {
2203 (ty::GenericParamDefKind::Type { .. }, ty::GenericArgKind::Type(_))
2204 | (ty::GenericParamDefKind::Lifetime, ty::GenericArgKind::Lifetime(_))
2205 | (ty::GenericParamDefKind::Const { .. }, ty::GenericArgKind::Const(_)) => {}
2213 let generics = tcx.generics_of(assoc_item.def_id);
2214 // Chop off any additional substs (RPITIT) substs
2215 let substs = &substs[0..generics.count().min(substs.len())];
2216 check_substs_compatible_inner(tcx, generics, substs)
2219 fn confirm_impl_trait_in_trait_candidate<'tcx>(
2220 selcx: &mut SelectionContext<'_, 'tcx>,
2221 obligation: &ProjectionTyObligation<'tcx>,
2222 data: ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>>,
2223 ) -> Progress<'tcx> {
2224 let tcx = selcx.tcx();
2225 let mut obligations = data.nested;
2227 let trait_fn_def_id = tcx.impl_trait_in_trait_parent(obligation.predicate.item_def_id);
2228 let Ok(leaf_def) = assoc_def(selcx, data.impl_def_id, trait_fn_def_id) else {
2229 return Progress { term: tcx.ty_error().into(), obligations };
2231 if !leaf_def.item.defaultness(tcx).has_value() {
2232 return Progress { term: tcx.ty_error().into(), obligations };
2235 // Use the default `impl Trait` for the trait, e.g., for a default trait body
2236 if leaf_def.item.container == ty::AssocItemContainer::TraitContainer {
2239 .mk_opaque(obligation.predicate.item_def_id, obligation.predicate.substs)
2245 // Rebase from {trait}::{fn}::{opaque} to {impl}::{fn}::{opaque},
2246 // since `data.substs` are the impl substs.
2247 let impl_fn_substs =
2248 obligation.predicate.substs.rebase_onto(tcx, tcx.parent(trait_fn_def_id), data.substs);
2249 let impl_fn_substs = translate_substs(
2251 obligation.param_env,
2254 leaf_def.defining_node,
2257 if !check_substs_compatible(tcx, &leaf_def.item, impl_fn_substs) {
2258 let err = tcx.ty_error_with_message(
2259 obligation.cause.span,
2260 "impl method and trait method have different parameters",
2262 return Progress { term: err.into(), obligations };
2265 let impl_fn_def_id = leaf_def.item.def_id;
2267 let cause = ObligationCause::new(
2268 obligation.cause.span,
2269 obligation.cause.body_id,
2270 super::ItemObligation(impl_fn_def_id),
2272 let predicates = normalize_with_depth_to(
2274 obligation.param_env,
2276 obligation.recursion_depth + 1,
2277 tcx.predicates_of(impl_fn_def_id).instantiate(tcx, impl_fn_substs),
2280 obligations.extend(std::iter::zip(predicates.predicates, predicates.spans).map(
2282 Obligation::with_depth(
2284 ObligationCause::new(
2285 obligation.cause.span,
2286 obligation.cause.body_id,
2287 if span.is_dummy() {
2288 super::ItemObligation(impl_fn_def_id)
2290 super::BindingObligation(impl_fn_def_id, span)
2293 obligation.recursion_depth + 1,
2294 obligation.param_env,
2300 let ty = normalize_with_depth_to(
2302 obligation.param_env,
2304 obligation.recursion_depth + 1,
2305 tcx.bound_trait_impl_trait_tys(impl_fn_def_id)
2307 tys.map_or_else(|_| tcx.ty_error(), |tys| tys[&obligation.predicate.item_def_id])
2309 .subst(tcx, impl_fn_substs),
2313 Progress { term: ty.into(), obligations }
2316 // Get obligations corresponding to the predicates from the where-clause of the
2317 // associated type itself.
2318 fn assoc_ty_own_obligations<'cx, 'tcx>(
2319 selcx: &mut SelectionContext<'cx, 'tcx>,
2320 obligation: &ProjectionTyObligation<'tcx>,
2321 nested: &mut Vec<PredicateObligation<'tcx>>,
2323 let tcx = selcx.tcx();
2324 for predicate in tcx
2325 .predicates_of(obligation.predicate.item_def_id)
2326 .instantiate_own(tcx, obligation.predicate.substs)
2329 let normalized = normalize_with_depth_to(
2331 obligation.param_env,
2332 obligation.cause.clone(),
2333 obligation.recursion_depth + 1,
2337 nested.push(Obligation::with_depth(
2339 obligation.cause.clone(),
2340 obligation.recursion_depth + 1,
2341 obligation.param_env,
2347 /// Locate the definition of an associated type in the specialization hierarchy,
2348 /// starting from the given impl.
2350 /// Based on the "projection mode", this lookup may in fact only examine the
2351 /// topmost impl. See the comments for `Reveal` for more details.
2353 selcx: &SelectionContext<'_, '_>,
2355 assoc_def_id: DefId,
2356 ) -> Result<specialization_graph::LeafDef, ErrorGuaranteed> {
2357 let tcx = selcx.tcx();
2358 let trait_def_id = tcx.impl_trait_ref(impl_def_id).unwrap().def_id;
2359 let trait_def = tcx.trait_def(trait_def_id);
2361 // This function may be called while we are still building the
2362 // specialization graph that is queried below (via TraitDef::ancestors()),
2363 // so, in order to avoid unnecessary infinite recursion, we manually look
2364 // for the associated item at the given impl.
2365 // If there is no such item in that impl, this function will fail with a
2366 // cycle error if the specialization graph is currently being built.
2367 if let Some(&impl_item_id) = tcx.impl_item_implementor_ids(impl_def_id).get(&assoc_def_id) {
2368 let item = tcx.associated_item(impl_item_id);
2369 let impl_node = specialization_graph::Node::Impl(impl_def_id);
2370 return Ok(specialization_graph::LeafDef {
2372 defining_node: impl_node,
2373 finalizing_node: if item.defaultness(tcx).is_default() {
2381 let ancestors = trait_def.ancestors(tcx, impl_def_id)?;
2382 if let Some(assoc_item) = ancestors.leaf_def(tcx, assoc_def_id) {
2385 // This is saying that neither the trait nor
2386 // the impl contain a definition for this
2387 // associated type. Normally this situation
2388 // could only arise through a compiler bug --
2389 // if the user wrote a bad item name, it
2390 // should have failed in astconv.
2392 "No associated type `{}` for {}",
2393 tcx.item_name(assoc_def_id),
2394 tcx.def_path_str(impl_def_id)
2399 pub(crate) trait ProjectionCacheKeyExt<'cx, 'tcx>: Sized {
2400 fn from_poly_projection_predicate(
2401 selcx: &mut SelectionContext<'cx, 'tcx>,
2402 predicate: ty::PolyProjectionPredicate<'tcx>,
2406 impl<'cx, 'tcx> ProjectionCacheKeyExt<'cx, 'tcx> for ProjectionCacheKey<'tcx> {
2407 fn from_poly_projection_predicate(
2408 selcx: &mut SelectionContext<'cx, 'tcx>,
2409 predicate: ty::PolyProjectionPredicate<'tcx>,
2411 let infcx = selcx.infcx;
2412 // We don't do cross-snapshot caching of obligations with escaping regions,
2413 // so there's no cache key to use
2414 predicate.no_bound_vars().map(|predicate| {
2415 ProjectionCacheKey::new(
2416 // We don't attempt to match up with a specific type-variable state
2417 // from a specific call to `opt_normalize_projection_type` - if
2418 // there's no precise match, the original cache entry is "stranded"
2420 infcx.resolve_vars_if_possible(predicate.projection_ty),