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::resolve::OpportunisticRegionResolver;
31 use rustc_infer::traits::ImplSourceBuiltinData;
32 use rustc_middle::traits::select::OverflowError;
33 use rustc_middle::ty::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable};
34 use rustc_middle::ty::visit::{MaxUniverse, TypeVisitable};
35 use rustc_middle::ty::DefIdTree;
36 use rustc_middle::ty::{self, Term, ToPredicate, Ty, TyCtxt};
37 use rustc_span::symbol::sym;
39 use std::collections::BTreeMap;
41 pub use rustc_middle::traits::Reveal;
43 pub type PolyProjectionObligation<'tcx> = Obligation<'tcx, ty::PolyProjectionPredicate<'tcx>>;
45 pub type ProjectionObligation<'tcx> = Obligation<'tcx, ty::ProjectionPredicate<'tcx>>;
47 pub type ProjectionTyObligation<'tcx> = Obligation<'tcx, ty::ProjectionTy<'tcx>>;
49 pub(super) struct InProgress;
51 /// When attempting to resolve `<T as TraitRef>::Name` ...
53 pub enum ProjectionError<'tcx> {
54 /// ...we found multiple sources of information and couldn't resolve the ambiguity.
57 /// ...an error occurred matching `T : TraitRef`
58 TraitSelectionError(SelectionError<'tcx>),
61 #[derive(PartialEq, Eq, Debug)]
62 enum ProjectionCandidate<'tcx> {
63 /// From a where-clause in the env or object type
64 ParamEnv(ty::PolyProjectionPredicate<'tcx>),
66 /// From the definition of `Trait` when you have something like
67 /// `<<A as Trait>::B as Trait2>::C`.
68 TraitDef(ty::PolyProjectionPredicate<'tcx>),
70 /// Bounds specified on an object type
71 Object(ty::PolyProjectionPredicate<'tcx>),
73 /// From an "impl" (or a "pseudo-impl" returned by select)
74 Select(Selection<'tcx>),
76 ImplTraitInTrait(ImplTraitInTraitCandidate<'tcx>),
79 #[derive(PartialEq, Eq, Debug)]
80 enum ImplTraitInTraitCandidate<'tcx> {
81 // The `impl Trait` from a trait function's default body
83 // A concrete type provided from a trait's `impl Trait` from an impl
84 Impl(ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>>),
87 enum ProjectionCandidateSet<'tcx> {
89 Single(ProjectionCandidate<'tcx>),
91 Error(SelectionError<'tcx>),
94 impl<'tcx> ProjectionCandidateSet<'tcx> {
95 fn mark_ambiguous(&mut self) {
96 *self = ProjectionCandidateSet::Ambiguous;
99 fn mark_error(&mut self, err: SelectionError<'tcx>) {
100 *self = ProjectionCandidateSet::Error(err);
103 // Returns true if the push was successful, or false if the candidate
104 // was discarded -- this could be because of ambiguity, or because
105 // a higher-priority candidate is already there.
106 fn push_candidate(&mut self, candidate: ProjectionCandidate<'tcx>) -> bool {
107 use self::ProjectionCandidate::*;
108 use self::ProjectionCandidateSet::*;
110 // This wacky variable is just used to try and
111 // make code readable and avoid confusing paths.
112 // It is assigned a "value" of `()` only on those
113 // paths in which we wish to convert `*self` to
114 // ambiguous (and return false, because the candidate
115 // was not used). On other paths, it is not assigned,
116 // and hence if those paths *could* reach the code that
117 // comes after the match, this fn would not compile.
118 let convert_to_ambiguous;
122 *self = Single(candidate);
127 // Duplicates can happen inside ParamEnv. In the case, we
128 // perform a lazy deduplication.
129 if current == &candidate {
133 // Prefer where-clauses. As in select, if there are multiple
134 // candidates, we prefer where-clause candidates over impls. This
135 // may seem a bit surprising, since impls are the source of
136 // "truth" in some sense, but in fact some of the impls that SEEM
137 // applicable are not, because of nested obligations. Where
138 // clauses are the safer choice. See the comment on
139 // `select::SelectionCandidate` and #21974 for more details.
140 match (current, candidate) {
141 (ParamEnv(..), ParamEnv(..)) => convert_to_ambiguous = (),
142 (ParamEnv(..), _) => return false,
143 (_, ParamEnv(..)) => unreachable!(),
144 (_, _) => convert_to_ambiguous = (),
148 Ambiguous | Error(..) => {
153 // We only ever get here when we moved from a single candidate
155 let () = convert_to_ambiguous;
161 /// States returned from `poly_project_and_unify_type`. Takes the place
162 /// of the old return type, which was:
163 /// ```ignore (not-rust)
165 /// Result<Option<Vec<PredicateObligation<'tcx>>>, InProgress>,
166 /// MismatchedProjectionTypes<'tcx>,
169 pub(super) enum ProjectAndUnifyResult<'tcx> {
170 /// The projection bound holds subject to the given obligations. If the
171 /// projection cannot be normalized because the required trait bound does
172 /// not hold, this is returned, with `obligations` being a predicate that
173 /// cannot be proven.
174 Holds(Vec<PredicateObligation<'tcx>>),
175 /// The projection cannot be normalized due to ambiguity. Resolving some
176 /// inference variables in the projection may fix this.
178 /// The project cannot be normalized because `poly_project_and_unify_type`
179 /// is called recursively while normalizing the same projection.
181 // the projection can be normalized, but is not equal to the expected type.
182 // Returns the type error that arose from the mismatch.
183 MismatchedProjectionTypes(MismatchedProjectionTypes<'tcx>),
186 /// Evaluates constraints of the form:
187 /// ```ignore (not-rust)
188 /// for<...> <T as Trait>::U == V
190 /// If successful, this may result in additional obligations. Also returns
191 /// the projection cache key used to track these additional obligations.
192 #[instrument(level = "debug", skip(selcx))]
193 pub(super) fn poly_project_and_unify_type<'cx, 'tcx>(
194 selcx: &mut SelectionContext<'cx, 'tcx>,
195 obligation: &PolyProjectionObligation<'tcx>,
196 ) -> ProjectAndUnifyResult<'tcx> {
197 let infcx = selcx.infcx;
198 let r = infcx.commit_if_ok(|_snapshot| {
199 let old_universe = infcx.universe();
200 let placeholder_predicate =
201 infcx.replace_bound_vars_with_placeholders(obligation.predicate);
202 let new_universe = infcx.universe();
204 let placeholder_obligation = obligation.with(infcx.tcx, placeholder_predicate);
205 match project_and_unify_type(selcx, &placeholder_obligation) {
206 ProjectAndUnifyResult::MismatchedProjectionTypes(e) => Err(e),
207 ProjectAndUnifyResult::Holds(obligations)
208 if old_universe != new_universe
209 && selcx.tcx().features().generic_associated_types_extended =>
211 // If the `generic_associated_types_extended` feature is active, then we ignore any
212 // obligations references lifetimes from any universe greater than or equal to the
213 // universe just created. Otherwise, we can end up with something like `for<'a> I: 'a`,
214 // which isn't quite what we want. Ideally, we want either an implied
215 // `for<'a where I: 'a> I: 'a` or we want to "lazily" check these hold when we
216 // substitute concrete regions. There is design work to be done here; until then,
217 // however, this allows experimenting potential GAT features without running into
218 // well-formedness issues.
219 let new_obligations = obligations
221 .filter(|obligation| {
222 let mut visitor = MaxUniverse::new();
223 obligation.predicate.visit_with(&mut visitor);
224 visitor.max_universe() < new_universe
227 Ok(ProjectAndUnifyResult::Holds(new_obligations))
235 Err(err) => ProjectAndUnifyResult::MismatchedProjectionTypes(err),
239 /// Evaluates constraints of the form:
240 /// ```ignore (not-rust)
241 /// <T as Trait>::U == V
243 /// If successful, this may result in additional obligations.
245 /// See [poly_project_and_unify_type] for an explanation of the return value.
246 #[instrument(level = "debug", skip(selcx))]
247 fn project_and_unify_type<'cx, 'tcx>(
248 selcx: &mut SelectionContext<'cx, 'tcx>,
249 obligation: &ProjectionObligation<'tcx>,
250 ) -> ProjectAndUnifyResult<'tcx> {
251 let mut obligations = vec![];
253 let infcx = selcx.infcx;
254 let normalized = match opt_normalize_projection_type(
256 obligation.param_env,
257 obligation.predicate.projection_ty,
258 obligation.cause.clone(),
259 obligation.recursion_depth,
263 Ok(None) => return ProjectAndUnifyResult::FailedNormalization,
264 Err(InProgress) => return ProjectAndUnifyResult::Recursive,
266 debug!(?normalized, ?obligations, "project_and_unify_type result");
267 let actual = obligation.predicate.term;
268 // For an example where this is necessary see src/test/ui/impl-trait/nested-return-type2.rs
269 // This allows users to omit re-mentioning all bounds on an associated type and just use an
270 // `impl Trait` for the assoc type to add more bounds.
271 let InferOk { value: actual, obligations: new } =
272 selcx.infcx.replace_opaque_types_with_inference_vars(
274 obligation.cause.body_id,
275 obligation.cause.span,
276 obligation.param_env,
278 obligations.extend(new);
280 match infcx.at(&obligation.cause, obligation.param_env).eq(normalized, actual) {
281 Ok(InferOk { obligations: inferred_obligations, value: () }) => {
282 obligations.extend(inferred_obligations);
283 ProjectAndUnifyResult::Holds(obligations)
286 debug!("equating types encountered error {:?}", err);
287 ProjectAndUnifyResult::MismatchedProjectionTypes(MismatchedProjectionTypes { err })
292 /// Normalizes any associated type projections in `value`, replacing
293 /// them with a fully resolved type where possible. The return value
294 /// combines the normalized result and any additional obligations that
295 /// were incurred as result.
296 pub fn normalize<'a, 'b, 'tcx, T>(
297 selcx: &'a mut SelectionContext<'b, 'tcx>,
298 param_env: ty::ParamEnv<'tcx>,
299 cause: ObligationCause<'tcx>,
301 ) -> Normalized<'tcx, T>
303 T: TypeFoldable<'tcx>,
305 let mut obligations = Vec::new();
306 let value = normalize_to(selcx, param_env, cause, value, &mut obligations);
307 Normalized { value, obligations }
310 pub fn normalize_to<'a, 'b, 'tcx, T>(
311 selcx: &'a mut SelectionContext<'b, 'tcx>,
312 param_env: ty::ParamEnv<'tcx>,
313 cause: ObligationCause<'tcx>,
315 obligations: &mut Vec<PredicateObligation<'tcx>>,
318 T: TypeFoldable<'tcx>,
320 normalize_with_depth_to(selcx, param_env, cause, 0, value, obligations)
323 /// As `normalize`, but with a custom depth.
324 pub fn normalize_with_depth<'a, 'b, 'tcx, T>(
325 selcx: &'a mut SelectionContext<'b, 'tcx>,
326 param_env: ty::ParamEnv<'tcx>,
327 cause: ObligationCause<'tcx>,
330 ) -> Normalized<'tcx, T>
332 T: TypeFoldable<'tcx>,
334 let mut obligations = Vec::new();
335 let value = normalize_with_depth_to(selcx, param_env, cause, depth, value, &mut obligations);
336 Normalized { value, obligations }
339 #[instrument(level = "info", skip(selcx, param_env, cause, obligations))]
340 pub fn normalize_with_depth_to<'a, 'b, 'tcx, T>(
341 selcx: &'a mut SelectionContext<'b, 'tcx>,
342 param_env: ty::ParamEnv<'tcx>,
343 cause: ObligationCause<'tcx>,
346 obligations: &mut Vec<PredicateObligation<'tcx>>,
349 T: TypeFoldable<'tcx>,
351 debug!(obligations.len = obligations.len());
352 let mut normalizer = AssocTypeNormalizer::new(selcx, param_env, cause, depth, obligations);
353 let result = ensure_sufficient_stack(|| normalizer.fold(value));
354 debug!(?result, obligations.len = normalizer.obligations.len());
355 debug!(?normalizer.obligations,);
359 #[instrument(level = "info", skip(selcx, param_env, cause, obligations))]
360 pub fn try_normalize_with_depth_to<'a, 'b, 'tcx, T>(
361 selcx: &'a mut SelectionContext<'b, 'tcx>,
362 param_env: ty::ParamEnv<'tcx>,
363 cause: ObligationCause<'tcx>,
366 obligations: &mut Vec<PredicateObligation<'tcx>>,
369 T: TypeFoldable<'tcx>,
371 debug!(obligations.len = obligations.len());
372 let mut normalizer = AssocTypeNormalizer::new_without_eager_inference_replacement(
379 let result = ensure_sufficient_stack(|| normalizer.fold(value));
380 debug!(?result, obligations.len = normalizer.obligations.len());
381 debug!(?normalizer.obligations,);
385 pub(crate) fn needs_normalization<'tcx, T: TypeVisitable<'tcx>>(value: &T, reveal: Reveal) -> bool {
387 Reveal::UserFacing => value
388 .has_type_flags(ty::TypeFlags::HAS_TY_PROJECTION | ty::TypeFlags::HAS_CT_PROJECTION),
389 Reveal::All => value.has_type_flags(
390 ty::TypeFlags::HAS_TY_PROJECTION
391 | ty::TypeFlags::HAS_TY_OPAQUE
392 | ty::TypeFlags::HAS_CT_PROJECTION,
397 struct AssocTypeNormalizer<'a, 'b, 'tcx> {
398 selcx: &'a mut SelectionContext<'b, 'tcx>,
399 param_env: ty::ParamEnv<'tcx>,
400 cause: ObligationCause<'tcx>,
401 obligations: &'a mut Vec<PredicateObligation<'tcx>>,
403 universes: Vec<Option<ty::UniverseIndex>>,
404 /// If true, when a projection is unable to be completed, an inference
405 /// variable will be created and an obligation registered to project to that
406 /// inference variable. Also, constants will be eagerly evaluated.
407 eager_inference_replacement: bool,
410 impl<'a, 'b, 'tcx> AssocTypeNormalizer<'a, 'b, 'tcx> {
412 selcx: &'a mut SelectionContext<'b, 'tcx>,
413 param_env: ty::ParamEnv<'tcx>,
414 cause: ObligationCause<'tcx>,
416 obligations: &'a mut Vec<PredicateObligation<'tcx>>,
417 ) -> AssocTypeNormalizer<'a, 'b, 'tcx> {
418 AssocTypeNormalizer {
425 eager_inference_replacement: true,
429 fn new_without_eager_inference_replacement(
430 selcx: &'a mut SelectionContext<'b, 'tcx>,
431 param_env: ty::ParamEnv<'tcx>,
432 cause: ObligationCause<'tcx>,
434 obligations: &'a mut Vec<PredicateObligation<'tcx>>,
435 ) -> AssocTypeNormalizer<'a, 'b, 'tcx> {
436 AssocTypeNormalizer {
443 eager_inference_replacement: false,
447 fn fold<T: TypeFoldable<'tcx>>(&mut self, value: T) -> T {
448 let value = self.selcx.infcx.resolve_vars_if_possible(value);
452 !value.has_escaping_bound_vars(),
453 "Normalizing {:?} without wrapping in a `Binder`",
457 if !needs_normalization(&value, self.param_env.reveal()) {
460 value.fold_with(self)
465 impl<'a, 'b, 'tcx> TypeFolder<'tcx> for AssocTypeNormalizer<'a, 'b, 'tcx> {
466 fn tcx<'c>(&'c self) -> TyCtxt<'tcx> {
470 fn fold_binder<T: TypeFoldable<'tcx>>(
472 t: ty::Binder<'tcx, T>,
473 ) -> ty::Binder<'tcx, T> {
474 self.universes.push(None);
475 let t = t.super_fold_with(self);
476 self.universes.pop();
480 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
481 if !needs_normalization(&ty, self.param_env.reveal()) {
485 // We try to be a little clever here as a performance optimization in
486 // cases where there are nested projections under binders.
489 // for<'a> fn(<T as Foo>::One<'a, Box<dyn Bar<'a, Item=<T as Foo>::Two<'a>>>>)
491 // We normalize the substs on the projection before the projecting, but
492 // if we're naive, we'll
493 // replace bound vars on inner, project inner, replace placeholders on inner,
494 // replace bound vars on outer, project outer, replace placeholders on outer
496 // However, if we're a bit more clever, we can replace the bound vars
497 // on the entire type before normalizing nested projections, meaning we
498 // replace bound vars on outer, project inner,
499 // project outer, replace placeholders on outer
501 // This is possible because the inner `'a` will already be a placeholder
502 // when we need to normalize the inner projection
504 // On the other hand, this does add a bit of complexity, since we only
505 // replace bound vars if the current type is a `Projection` and we need
506 // to make sure we don't forget to fold the substs regardless.
509 // This is really important. While we *can* handle this, this has
510 // severe performance implications for large opaque types with
511 // late-bound regions. See `issue-88862` benchmark.
512 ty::Opaque(def_id, substs) if !substs.has_escaping_bound_vars() => {
513 // Only normalize `impl Trait` outside of type inference, usually in codegen.
514 match self.param_env.reveal() {
515 Reveal::UserFacing => ty.super_fold_with(self),
518 let recursion_limit = self.tcx().recursion_limit();
519 if !recursion_limit.value_within_limit(self.depth) {
520 let obligation = Obligation::with_depth(
527 self.selcx.infcx.err_ctxt().report_overflow_error(&obligation, true);
530 let substs = substs.fold_with(self);
531 let generic_ty = self.tcx().bound_type_of(def_id);
532 let concrete_ty = generic_ty.subst(self.tcx(), substs);
534 let folded_ty = self.fold_ty(concrete_ty);
541 ty::Projection(data) if !data.has_escaping_bound_vars() => {
542 // This branch is *mostly* just an optimization: when we don't
543 // have escaping bound vars, we don't need to replace them with
544 // placeholders (see branch below). *Also*, we know that we can
545 // register an obligation to *later* project, since we know
546 // there won't be bound vars there.
547 let data = data.fold_with(self);
548 let normalized_ty = if self.eager_inference_replacement {
549 normalize_projection_type(
555 &mut self.obligations,
558 opt_normalize_projection_type(
564 &mut self.obligations,
568 .unwrap_or_else(|| ty.super_fold_with(self).into())
574 obligations.len = ?self.obligations.len(),
575 "AssocTypeNormalizer: normalized type"
577 normalized_ty.ty().unwrap()
580 ty::Projection(data) => {
581 // If there are escaping bound vars, we temporarily replace the
582 // bound vars with placeholders. Note though, that in the case
583 // that we still can't project for whatever reason (e.g. self
584 // type isn't known enough), we *can't* register an obligation
585 // and return an inference variable (since then that obligation
586 // would have bound vars and that's a can of worms). Instead,
587 // we just give up and fall back to pretending like we never tried!
589 // Note: this isn't necessarily the final approach here; we may
590 // want to figure out how to register obligations with escaping vars
591 // or handle this some other way.
593 let infcx = self.selcx.infcx;
594 let (data, mapped_regions, mapped_types, mapped_consts) =
595 BoundVarReplacer::replace_bound_vars(infcx, &mut self.universes, data);
596 let data = data.fold_with(self);
597 let normalized_ty = opt_normalize_projection_type(
603 &mut self.obligations,
607 .map(|term| term.ty().unwrap())
608 .map(|normalized_ty| {
609 PlaceholderReplacer::replace_placeholders(
618 .unwrap_or_else(|| ty.super_fold_with(self));
624 obligations.len = ?self.obligations.len(),
625 "AssocTypeNormalizer: normalized type"
630 _ => ty.super_fold_with(self),
634 #[instrument(skip(self), level = "debug")]
635 fn fold_const(&mut self, constant: ty::Const<'tcx>) -> ty::Const<'tcx> {
636 let tcx = self.selcx.tcx();
637 if tcx.lazy_normalization() || !needs_normalization(&constant, self.param_env.reveal()) {
640 let constant = constant.super_fold_with(self);
641 debug!(?constant, ?self.param_env);
642 with_replaced_escaping_bound_vars(
646 |constant| constant.eval(tcx, self.param_env),
652 fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
653 if p.allow_normalization() && needs_normalization(&p, self.param_env.reveal()) {
654 p.super_fold_with(self)
661 pub struct BoundVarReplacer<'me, 'tcx> {
662 infcx: &'me InferCtxt<'tcx>,
663 // These three maps track the bound variable that were replaced by placeholders. It might be
664 // nice to remove these since we already have the `kind` in the placeholder; we really just need
665 // the `var` (but we *could* bring that into scope if we were to track them as we pass them).
666 mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
667 mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy>,
668 mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
669 // The current depth relative to *this* folding, *not* the entire normalization. In other words,
670 // the depth of binders we've passed here.
671 current_index: ty::DebruijnIndex,
672 // The `UniverseIndex` of the binding levels above us. These are optional, since we are lazy:
673 // we don't actually create a universe until we see a bound var we have to replace.
674 universe_indices: &'me mut Vec<Option<ty::UniverseIndex>>,
677 /// Executes `f` on `value` after replacing all escaping bound variables with placeholders
678 /// and then replaces these placeholders with the original bound variables in the result.
680 /// In most places, bound variables should be replaced right when entering a binder, making
681 /// this function unnecessary. However, normalization currently does not do that, so we have
682 /// to do this lazily.
684 /// You should not add any additional uses of this function, at least not without first
685 /// discussing it with t-types.
687 /// FIXME(@lcnr): We may even consider experimenting with eagerly replacing bound vars during
688 /// normalization as well, at which point this function will be unnecessary and can be removed.
689 pub fn with_replaced_escaping_bound_vars<'a, 'tcx, T: TypeFoldable<'tcx>, R: TypeFoldable<'tcx>>(
690 infcx: &'a InferCtxt<'tcx>,
691 universe_indices: &'a mut Vec<Option<ty::UniverseIndex>>,
693 f: impl FnOnce(T) -> R,
695 if value.has_escaping_bound_vars() {
696 let (value, mapped_regions, mapped_types, mapped_consts) =
697 BoundVarReplacer::replace_bound_vars(infcx, universe_indices, value);
698 let result = f(value);
699 PlaceholderReplacer::replace_placeholders(
712 impl<'me, 'tcx> BoundVarReplacer<'me, 'tcx> {
713 /// Returns `Some` if we *were* able to replace bound vars. If there are any bound vars that
714 /// use a binding level above `universe_indices.len()`, we fail.
715 pub fn replace_bound_vars<T: TypeFoldable<'tcx>>(
716 infcx: &'me InferCtxt<'tcx>,
717 universe_indices: &'me mut Vec<Option<ty::UniverseIndex>>,
721 BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
722 BTreeMap<ty::PlaceholderType, ty::BoundTy>,
723 BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
725 let mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion> = BTreeMap::new();
726 let mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy> = BTreeMap::new();
727 let mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar> = BTreeMap::new();
729 let mut replacer = BoundVarReplacer {
734 current_index: ty::INNERMOST,
738 let value = value.fold_with(&mut replacer);
740 (value, replacer.mapped_regions, replacer.mapped_types, replacer.mapped_consts)
743 fn universe_for(&mut self, debruijn: ty::DebruijnIndex) -> ty::UniverseIndex {
744 let infcx = self.infcx;
746 self.universe_indices.len() + self.current_index.as_usize() - debruijn.as_usize() - 1;
747 let universe = self.universe_indices[index].unwrap_or_else(|| {
748 for i in self.universe_indices.iter_mut().take(index + 1) {
749 *i = i.or_else(|| Some(infcx.create_next_universe()))
751 self.universe_indices[index].unwrap()
757 impl<'tcx> TypeFolder<'tcx> for BoundVarReplacer<'_, 'tcx> {
758 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
762 fn fold_binder<T: TypeFoldable<'tcx>>(
764 t: ty::Binder<'tcx, T>,
765 ) -> ty::Binder<'tcx, T> {
766 self.current_index.shift_in(1);
767 let t = t.super_fold_with(self);
768 self.current_index.shift_out(1);
772 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
774 ty::ReLateBound(debruijn, _)
775 if debruijn.as_usize() + 1
776 > self.current_index.as_usize() + self.universe_indices.len() =>
778 bug!("Bound vars outside of `self.universe_indices`");
780 ty::ReLateBound(debruijn, br) if debruijn >= self.current_index => {
781 let universe = self.universe_for(debruijn);
782 let p = ty::PlaceholderRegion { universe, name: br.kind };
783 self.mapped_regions.insert(p, br);
784 self.infcx.tcx.mk_region(ty::RePlaceholder(p))
790 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
792 ty::Bound(debruijn, _)
793 if debruijn.as_usize() + 1
794 > self.current_index.as_usize() + self.universe_indices.len() =>
796 bug!("Bound vars outside of `self.universe_indices`");
798 ty::Bound(debruijn, bound_ty) if debruijn >= self.current_index => {
799 let universe = self.universe_for(debruijn);
800 let p = ty::PlaceholderType { universe, name: bound_ty.var };
801 self.mapped_types.insert(p, bound_ty);
802 self.infcx.tcx.mk_ty(ty::Placeholder(p))
804 _ if t.has_vars_bound_at_or_above(self.current_index) => t.super_fold_with(self),
809 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
811 ty::ConstKind::Bound(debruijn, _)
812 if debruijn.as_usize() + 1
813 > self.current_index.as_usize() + self.universe_indices.len() =>
815 bug!("Bound vars outside of `self.universe_indices`");
817 ty::ConstKind::Bound(debruijn, bound_const) if debruijn >= self.current_index => {
818 let universe = self.universe_for(debruijn);
819 let p = ty::PlaceholderConst { universe, name: bound_const };
820 self.mapped_consts.insert(p, bound_const);
821 self.infcx.tcx.mk_const(p, ct.ty())
823 _ => ct.super_fold_with(self),
827 fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
828 if p.has_vars_bound_at_or_above(self.current_index) { p.super_fold_with(self) } else { p }
832 /// The inverse of [`BoundVarReplacer`]: replaces placeholders with the bound vars from which they came.
833 pub struct PlaceholderReplacer<'me, 'tcx> {
834 infcx: &'me InferCtxt<'tcx>,
835 mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
836 mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy>,
837 mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
838 universe_indices: &'me [Option<ty::UniverseIndex>],
839 current_index: ty::DebruijnIndex,
842 impl<'me, 'tcx> PlaceholderReplacer<'me, 'tcx> {
843 pub fn replace_placeholders<T: TypeFoldable<'tcx>>(
844 infcx: &'me InferCtxt<'tcx>,
845 mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
846 mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy>,
847 mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
848 universe_indices: &'me [Option<ty::UniverseIndex>],
851 let mut replacer = PlaceholderReplacer {
857 current_index: ty::INNERMOST,
859 value.fold_with(&mut replacer)
863 impl<'tcx> TypeFolder<'tcx> for PlaceholderReplacer<'_, 'tcx> {
864 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
868 fn fold_binder<T: TypeFoldable<'tcx>>(
870 t: ty::Binder<'tcx, T>,
871 ) -> ty::Binder<'tcx, T> {
872 if !t.has_placeholders() && !t.has_infer_regions() {
875 self.current_index.shift_in(1);
876 let t = t.super_fold_with(self);
877 self.current_index.shift_out(1);
881 fn fold_region(&mut self, r0: ty::Region<'tcx>) -> ty::Region<'tcx> {
887 .unwrap_region_constraints()
888 .opportunistic_resolve_region(self.infcx.tcx, r0),
893 ty::RePlaceholder(p) => {
894 let replace_var = self.mapped_regions.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_region(ty::ReLateBound(db, *replace_var))
913 debug!(?r0, ?r1, ?r2, "fold_region");
918 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
920 ty::Placeholder(p) => {
921 let replace_var = self.mapped_types.get(&p);
923 Some(replace_var) => {
927 .position(|u| matches!(u, Some(pu) if *pu == p.universe))
928 .unwrap_or_else(|| bug!("Unexpected placeholder universe."));
929 let db = ty::DebruijnIndex::from_usize(
930 self.universe_indices.len() - index + self.current_index.as_usize() - 1,
932 self.tcx().mk_ty(ty::Bound(db, *replace_var))
938 _ if ty.has_placeholders() || ty.has_infer_regions() => ty.super_fold_with(self),
943 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
944 if let ty::ConstKind::Placeholder(p) = ct.kind() {
945 let replace_var = self.mapped_consts.get(&p);
947 Some(replace_var) => {
951 .position(|u| matches!(u, Some(pu) if *pu == p.universe))
952 .unwrap_or_else(|| bug!("Unexpected placeholder universe."));
953 let db = ty::DebruijnIndex::from_usize(
954 self.universe_indices.len() - index + self.current_index.as_usize() - 1,
956 self.tcx().mk_const(ty::ConstKind::Bound(db, *replace_var), ct.ty())
961 ct.super_fold_with(self)
966 /// The guts of `normalize`: normalize a specific projection like `<T
967 /// as Trait>::Item`. The result is always a type (and possibly
968 /// additional obligations). If ambiguity arises, which implies that
969 /// there are unresolved type variables in the projection, we will
970 /// substitute a fresh type variable `$X` and generate a new
971 /// obligation `<T as Trait>::Item == $X` for later.
972 pub fn normalize_projection_type<'a, 'b, 'tcx>(
973 selcx: &'a mut SelectionContext<'b, 'tcx>,
974 param_env: ty::ParamEnv<'tcx>,
975 projection_ty: ty::ProjectionTy<'tcx>,
976 cause: ObligationCause<'tcx>,
978 obligations: &mut Vec<PredicateObligation<'tcx>>,
980 opt_normalize_projection_type(
990 .unwrap_or_else(move || {
991 // if we bottom out in ambiguity, create a type variable
992 // and a deferred predicate to resolve this when more type
993 // information is available.
995 selcx.infcx.infer_projection(param_env, projection_ty, cause, depth + 1, obligations).into()
999 /// The guts of `normalize`: normalize a specific projection like `<T
1000 /// as Trait>::Item`. The result is always a type (and possibly
1001 /// additional obligations). Returns `None` in the case of ambiguity,
1002 /// which indicates that there are unbound type variables.
1004 /// This function used to return `Option<NormalizedTy<'tcx>>`, which contains a
1005 /// `Ty<'tcx>` and an obligations vector. But that obligation vector was very
1006 /// often immediately appended to another obligations vector. So now this
1007 /// function takes an obligations vector and appends to it directly, which is
1008 /// slightly uglier but avoids the need for an extra short-lived allocation.
1009 #[instrument(level = "debug", skip(selcx, param_env, cause, obligations))]
1010 fn opt_normalize_projection_type<'a, 'b, 'tcx>(
1011 selcx: &'a mut SelectionContext<'b, 'tcx>,
1012 param_env: ty::ParamEnv<'tcx>,
1013 projection_ty: ty::ProjectionTy<'tcx>,
1014 cause: ObligationCause<'tcx>,
1016 obligations: &mut Vec<PredicateObligation<'tcx>>,
1017 ) -> Result<Option<Term<'tcx>>, InProgress> {
1018 let infcx = selcx.infcx;
1019 // Don't use the projection cache in intercrate mode -
1020 // the `infcx` may be re-used between intercrate in non-intercrate
1021 // mode, which could lead to using incorrect cache results.
1022 let use_cache = !selcx.is_intercrate();
1024 let projection_ty = infcx.resolve_vars_if_possible(projection_ty);
1025 let cache_key = ProjectionCacheKey::new(projection_ty);
1027 // FIXME(#20304) For now, I am caching here, which is good, but it
1028 // means we don't capture the type variables that are created in
1029 // the case of ambiguity. Which means we may create a large stream
1030 // of such variables. OTOH, if we move the caching up a level, we
1031 // would not benefit from caching when proving `T: Trait<U=Foo>`
1032 // bounds. It might be the case that we want two distinct caches,
1033 // or else another kind of cache entry.
1035 let cache_result = if use_cache {
1036 infcx.inner.borrow_mut().projection_cache().try_start(cache_key)
1040 match cache_result {
1041 Ok(()) => debug!("no cache"),
1042 Err(ProjectionCacheEntry::Ambiguous) => {
1043 // If we found ambiguity the last time, that means we will continue
1044 // to do so until some type in the key changes (and we know it
1045 // hasn't, because we just fully resolved it).
1046 debug!("found cache entry: ambiguous");
1049 Err(ProjectionCacheEntry::InProgress) => {
1050 // Under lazy normalization, this can arise when
1051 // bootstrapping. That is, imagine an environment with a
1052 // where-clause like `A::B == u32`. Now, if we are asked
1053 // to normalize `A::B`, we will want to check the
1054 // where-clauses in scope. So we will try to unify `A::B`
1055 // with `A::B`, which can trigger a recursive
1058 debug!("found cache entry: in-progress");
1060 // Cache that normalizing this projection resulted in a cycle. This
1061 // should ensure that, unless this happens within a snapshot that's
1062 // rolled back, fulfillment or evaluation will notice the cycle.
1065 infcx.inner.borrow_mut().projection_cache().recur(cache_key);
1067 return Err(InProgress);
1069 Err(ProjectionCacheEntry::Recur) => {
1070 debug!("recur cache");
1071 return Err(InProgress);
1073 Err(ProjectionCacheEntry::NormalizedTy { ty, complete: _ }) => {
1074 // This is the hottest path in this function.
1076 // If we find the value in the cache, then return it along
1077 // with the obligations that went along with it. Note
1078 // that, when using a fulfillment context, these
1079 // obligations could in principle be ignored: they have
1080 // already been registered when the cache entry was
1081 // created (and hence the new ones will quickly be
1082 // discarded as duplicated). But when doing trait
1083 // evaluation this is not the case, and dropping the trait
1084 // evaluations can causes ICEs (e.g., #43132).
1085 debug!(?ty, "found normalized ty");
1086 obligations.extend(ty.obligations);
1087 return Ok(Some(ty.value));
1089 Err(ProjectionCacheEntry::Error) => {
1090 debug!("opt_normalize_projection_type: found error");
1091 let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth);
1092 obligations.extend(result.obligations);
1093 return Ok(Some(result.value.into()));
1098 Obligation::with_depth(selcx.tcx(), cause.clone(), depth, param_env, projection_ty);
1100 match project(selcx, &obligation) {
1101 Ok(Projected::Progress(Progress {
1102 term: projected_term,
1103 obligations: mut projected_obligations,
1105 // if projection succeeded, then what we get out of this
1106 // is also non-normalized (consider: it was derived from
1107 // an impl, where-clause etc) and hence we must
1110 let projected_term = selcx.infcx.resolve_vars_if_possible(projected_term);
1112 let mut result = if projected_term.has_projections() {
1113 let mut normalizer = AssocTypeNormalizer::new(
1118 &mut projected_obligations,
1120 let normalized_ty = normalizer.fold(projected_term);
1122 Normalized { value: normalized_ty, obligations: projected_obligations }
1124 Normalized { value: projected_term, obligations: projected_obligations }
1127 let mut deduped: SsoHashSet<_> = Default::default();
1128 result.obligations.drain_filter(|projected_obligation| {
1129 if !deduped.insert(projected_obligation.clone()) {
1136 infcx.inner.borrow_mut().projection_cache().insert_term(cache_key, result.clone());
1138 obligations.extend(result.obligations);
1139 Ok(Some(result.value))
1141 Ok(Projected::NoProgress(projected_ty)) => {
1142 let result = Normalized { value: projected_ty, obligations: vec![] };
1144 infcx.inner.borrow_mut().projection_cache().insert_term(cache_key, result.clone());
1146 // No need to extend `obligations`.
1147 Ok(Some(result.value))
1149 Err(ProjectionError::TooManyCandidates) => {
1150 debug!("opt_normalize_projection_type: too many candidates");
1152 infcx.inner.borrow_mut().projection_cache().ambiguous(cache_key);
1156 Err(ProjectionError::TraitSelectionError(_)) => {
1157 debug!("opt_normalize_projection_type: ERROR");
1158 // if we got an error processing the `T as Trait` part,
1159 // just return `ty::err` but add the obligation `T :
1160 // Trait`, which when processed will cause the error to be
1164 infcx.inner.borrow_mut().projection_cache().error(cache_key);
1166 let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth);
1167 obligations.extend(result.obligations);
1168 Ok(Some(result.value.into()))
1173 /// If we are projecting `<T as Trait>::Item`, but `T: Trait` does not
1174 /// hold. In various error cases, we cannot generate a valid
1175 /// normalized projection. Therefore, we create an inference variable
1176 /// return an associated obligation that, when fulfilled, will lead to
1179 /// Note that we used to return `Error` here, but that was quite
1180 /// dubious -- the premise was that an error would *eventually* be
1181 /// reported, when the obligation was processed. But in general once
1182 /// you see an `Error` you are supposed to be able to assume that an
1183 /// error *has been* reported, so that you can take whatever heuristic
1184 /// paths you want to take. To make things worse, it was possible for
1185 /// cycles to arise, where you basically had a setup like `<MyType<$0>
1186 /// as Trait>::Foo == $0`. Here, normalizing `<MyType<$0> as
1187 /// Trait>::Foo> to `[type error]` would lead to an obligation of
1188 /// `<MyType<[type error]> as Trait>::Foo`. We are supposed to report
1189 /// an error for this obligation, but we legitimately should not,
1190 /// because it contains `[type error]`. Yuck! (See issue #29857 for
1191 /// one case where this arose.)
1192 fn normalize_to_error<'a, 'tcx>(
1193 selcx: &mut SelectionContext<'a, 'tcx>,
1194 param_env: ty::ParamEnv<'tcx>,
1195 projection_ty: ty::ProjectionTy<'tcx>,
1196 cause: ObligationCause<'tcx>,
1198 ) -> NormalizedTy<'tcx> {
1199 let trait_ref = ty::Binder::dummy(projection_ty.trait_ref(selcx.tcx()));
1200 let trait_obligation = Obligation {
1202 recursion_depth: depth,
1204 predicate: trait_ref.without_const().to_predicate(selcx.tcx()),
1206 let tcx = selcx.infcx.tcx;
1207 let def_id = projection_ty.item_def_id;
1208 let new_value = selcx.infcx.next_ty_var(TypeVariableOrigin {
1209 kind: TypeVariableOriginKind::NormalizeProjectionType,
1210 span: tcx.def_span(def_id),
1212 Normalized { value: new_value, obligations: vec![trait_obligation] }
1215 enum Projected<'tcx> {
1216 Progress(Progress<'tcx>),
1217 NoProgress(ty::Term<'tcx>),
1220 struct Progress<'tcx> {
1221 term: ty::Term<'tcx>,
1222 obligations: Vec<PredicateObligation<'tcx>>,
1225 impl<'tcx> Progress<'tcx> {
1226 fn error(tcx: TyCtxt<'tcx>) -> Self {
1227 Progress { term: tcx.ty_error().into(), obligations: vec![] }
1230 fn with_addl_obligations(mut self, mut obligations: Vec<PredicateObligation<'tcx>>) -> Self {
1231 self.obligations.append(&mut obligations);
1236 /// Computes the result of a projection type (if we can).
1239 /// - `obligation` must be fully normalized
1240 #[instrument(level = "info", skip(selcx))]
1241 fn project<'cx, 'tcx>(
1242 selcx: &mut SelectionContext<'cx, 'tcx>,
1243 obligation: &ProjectionTyObligation<'tcx>,
1244 ) -> Result<Projected<'tcx>, ProjectionError<'tcx>> {
1245 if !selcx.tcx().recursion_limit().value_within_limit(obligation.recursion_depth) {
1246 // This should really be an immediate error, but some existing code
1247 // relies on being able to recover from this.
1248 return Err(ProjectionError::TraitSelectionError(SelectionError::Overflow(
1249 OverflowError::Canonical,
1253 if obligation.predicate.references_error() {
1254 return Ok(Projected::Progress(Progress::error(selcx.tcx())));
1257 let mut candidates = ProjectionCandidateSet::None;
1259 assemble_candidate_for_impl_trait_in_trait(selcx, obligation, &mut candidates);
1261 // Make sure that the following procedures are kept in order. ParamEnv
1262 // needs to be first because it has highest priority, and Select checks
1263 // the return value of push_candidate which assumes it's ran at last.
1264 assemble_candidates_from_param_env(selcx, obligation, &mut candidates);
1266 assemble_candidates_from_trait_def(selcx, obligation, &mut candidates);
1268 assemble_candidates_from_object_ty(selcx, obligation, &mut candidates);
1270 if let ProjectionCandidateSet::Single(ProjectionCandidate::Object(_)) = candidates {
1271 // Avoid normalization cycle from selection (see
1272 // `assemble_candidates_from_object_ty`).
1273 // FIXME(lazy_normalization): Lazy normalization should save us from
1274 // having to special case this.
1276 assemble_candidates_from_impls(selcx, obligation, &mut candidates);
1280 ProjectionCandidateSet::Single(candidate) => {
1281 Ok(Projected::Progress(confirm_candidate(selcx, obligation, candidate)))
1283 ProjectionCandidateSet::None => Ok(Projected::NoProgress(
1284 // FIXME(associated_const_generics): this may need to change in the future?
1285 // need to investigate whether or not this is fine.
1288 .mk_projection(obligation.predicate.item_def_id, obligation.predicate.substs)
1291 // Error occurred while trying to processing impls.
1292 ProjectionCandidateSet::Error(e) => Err(ProjectionError::TraitSelectionError(e)),
1293 // Inherent ambiguity that prevents us from even enumerating the
1295 ProjectionCandidateSet::Ambiguous => Err(ProjectionError::TooManyCandidates),
1299 /// If the predicate's item is an `ImplTraitPlaceholder`, we do a select on the
1300 /// corresponding trait ref. If this yields an `impl`, then we're able to project
1301 /// to a concrete type, since we have an `impl`'s method to provide the RPITIT.
1302 fn assemble_candidate_for_impl_trait_in_trait<'cx, 'tcx>(
1303 selcx: &mut SelectionContext<'cx, 'tcx>,
1304 obligation: &ProjectionTyObligation<'tcx>,
1305 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1307 let tcx = selcx.tcx();
1308 if tcx.def_kind(obligation.predicate.item_def_id) == DefKind::ImplTraitPlaceholder {
1309 let trait_fn_def_id = tcx.impl_trait_in_trait_parent(obligation.predicate.item_def_id);
1310 // If we are trying to project an RPITIT with trait's default `Self` parameter,
1311 // then we must be within a default trait body.
1312 if obligation.predicate.self_ty()
1313 == ty::InternalSubsts::identity_for_item(tcx, obligation.predicate.item_def_id)
1315 && tcx.associated_item(trait_fn_def_id).defaultness(tcx).has_value()
1317 candidate_set.push_candidate(ProjectionCandidate::ImplTraitInTrait(
1318 ImplTraitInTraitCandidate::Trait,
1323 let trait_def_id = tcx.parent(trait_fn_def_id);
1325 obligation.predicate.substs.truncate_to(tcx, tcx.generics_of(trait_def_id));
1326 // FIXME(named-returns): Binders
1327 let trait_predicate =
1328 ty::Binder::dummy(ty::TraitRef { def_id: trait_def_id, substs: trait_substs });
1330 let _ = selcx.infcx.commit_if_ok(|_| {
1331 match selcx.select(&obligation.with(tcx, trait_predicate)) {
1332 Ok(Some(super::ImplSource::UserDefined(data))) => {
1333 candidate_set.push_candidate(ProjectionCandidate::ImplTraitInTrait(
1334 ImplTraitInTraitCandidate::Impl(data),
1339 candidate_set.mark_ambiguous();
1343 // Don't know enough about the impl to provide a useful signature
1347 debug!(error = ?e, "selection error");
1348 candidate_set.mark_error(e);
1356 /// The first thing we have to do is scan through the parameter
1357 /// environment to see whether there are any projection predicates
1358 /// there that can answer this question.
1359 fn assemble_candidates_from_param_env<'cx, 'tcx>(
1360 selcx: &mut SelectionContext<'cx, 'tcx>,
1361 obligation: &ProjectionTyObligation<'tcx>,
1362 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1364 assemble_candidates_from_predicates(
1368 ProjectionCandidate::ParamEnv,
1369 obligation.param_env.caller_bounds().iter(),
1374 /// In the case of a nested projection like `<<A as Foo>::FooT as Bar>::BarT`, we may find
1375 /// that the definition of `Foo` has some clues:
1377 /// ```ignore (illustrative)
1379 /// type FooT : Bar<BarT=i32>
1383 /// Here, for example, we could conclude that the result is `i32`.
1384 fn assemble_candidates_from_trait_def<'cx, 'tcx>(
1385 selcx: &mut SelectionContext<'cx, 'tcx>,
1386 obligation: &ProjectionTyObligation<'tcx>,
1387 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1389 debug!("assemble_candidates_from_trait_def(..)");
1391 let tcx = selcx.tcx();
1392 // Check whether the self-type is itself a projection.
1393 // If so, extract what we know from the trait and try to come up with a good answer.
1394 let bounds = match *obligation.predicate.self_ty().kind() {
1395 ty::Projection(ref data) => tcx.bound_item_bounds(data.item_def_id).subst(tcx, data.substs),
1396 ty::Opaque(def_id, substs) => tcx.bound_item_bounds(def_id).subst(tcx, substs),
1397 ty::Infer(ty::TyVar(_)) => {
1398 // If the self-type is an inference variable, then it MAY wind up
1399 // being a projected type, so induce an ambiguity.
1400 candidate_set.mark_ambiguous();
1406 assemble_candidates_from_predicates(
1410 ProjectionCandidate::TraitDef,
1416 /// In the case of a trait object like
1417 /// `<dyn Iterator<Item = ()> as Iterator>::Item` we can use the existential
1418 /// predicate in the trait object.
1420 /// We don't go through the select candidate for these bounds to avoid cycles:
1421 /// In the above case, `dyn Iterator<Item = ()>: Iterator` would create a
1422 /// nested obligation of `<dyn Iterator<Item = ()> as Iterator>::Item: Sized`,
1423 /// this then has to be normalized without having to prove
1424 /// `dyn Iterator<Item = ()>: Iterator` again.
1425 fn assemble_candidates_from_object_ty<'cx, 'tcx>(
1426 selcx: &mut SelectionContext<'cx, 'tcx>,
1427 obligation: &ProjectionTyObligation<'tcx>,
1428 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1430 debug!("assemble_candidates_from_object_ty(..)");
1432 let tcx = selcx.tcx();
1434 let self_ty = obligation.predicate.self_ty();
1435 let object_ty = selcx.infcx.shallow_resolve(self_ty);
1436 let data = match object_ty.kind() {
1437 ty::Dynamic(data, ..) => data,
1438 ty::Infer(ty::TyVar(_)) => {
1439 // If the self-type is an inference variable, then it MAY wind up
1440 // being an object type, so induce an ambiguity.
1441 candidate_set.mark_ambiguous();
1446 let env_predicates = data
1447 .projection_bounds()
1448 .filter(|bound| bound.item_def_id() == obligation.predicate.item_def_id)
1449 .map(|p| p.with_self_ty(tcx, object_ty).to_predicate(tcx));
1451 assemble_candidates_from_predicates(
1455 ProjectionCandidate::Object,
1463 skip(selcx, candidate_set, ctor, env_predicates, potentially_unnormalized_candidates)
1465 fn assemble_candidates_from_predicates<'cx, 'tcx>(
1466 selcx: &mut SelectionContext<'cx, 'tcx>,
1467 obligation: &ProjectionTyObligation<'tcx>,
1468 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1469 ctor: fn(ty::PolyProjectionPredicate<'tcx>) -> ProjectionCandidate<'tcx>,
1470 env_predicates: impl Iterator<Item = ty::Predicate<'tcx>>,
1471 potentially_unnormalized_candidates: bool,
1473 let infcx = selcx.infcx;
1474 for predicate in env_predicates {
1475 let bound_predicate = predicate.kind();
1476 if let ty::PredicateKind::Clause(ty::Clause::Projection(data)) =
1477 predicate.kind().skip_binder()
1479 let data = bound_predicate.rebind(data);
1480 if data.projection_def_id() != obligation.predicate.item_def_id {
1484 let is_match = infcx.probe(|_| {
1485 selcx.match_projection_projections(
1488 potentially_unnormalized_candidates,
1493 ProjectionMatchesProjection::Yes => {
1494 candidate_set.push_candidate(ctor(data));
1496 if potentially_unnormalized_candidates
1497 && !obligation.predicate.has_non_region_infer()
1499 // HACK: Pick the first trait def candidate for a fully
1500 // inferred predicate. This is to allow duplicates that
1501 // differ only in normalization.
1505 ProjectionMatchesProjection::Ambiguous => {
1506 candidate_set.mark_ambiguous();
1508 ProjectionMatchesProjection::No => {}
1514 #[instrument(level = "debug", skip(selcx, obligation, candidate_set))]
1515 fn assemble_candidates_from_impls<'cx, 'tcx>(
1516 selcx: &mut SelectionContext<'cx, 'tcx>,
1517 obligation: &ProjectionTyObligation<'tcx>,
1518 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1520 // Can't assemble candidate from impl for RPITIT
1521 if selcx.tcx().def_kind(obligation.predicate.item_def_id) == DefKind::ImplTraitPlaceholder {
1525 // If we are resolving `<T as TraitRef<...>>::Item == Type`,
1526 // start out by selecting the predicate `T as TraitRef<...>`:
1527 let poly_trait_ref = ty::Binder::dummy(obligation.predicate.trait_ref(selcx.tcx()));
1528 let trait_obligation = obligation.with(selcx.tcx(), poly_trait_ref);
1529 let _ = selcx.infcx.commit_if_ok(|_| {
1530 let impl_source = match selcx.select(&trait_obligation) {
1531 Ok(Some(impl_source)) => impl_source,
1533 candidate_set.mark_ambiguous();
1537 debug!(error = ?e, "selection error");
1538 candidate_set.mark_error(e);
1543 let eligible = match &impl_source {
1544 super::ImplSource::Closure(_)
1545 | super::ImplSource::Generator(_)
1546 | super::ImplSource::Future(_)
1547 | super::ImplSource::FnPointer(_)
1548 | super::ImplSource::TraitAlias(_) => true,
1549 super::ImplSource::UserDefined(impl_data) => {
1550 // We have to be careful when projecting out of an
1551 // impl because of specialization. If we are not in
1552 // codegen (i.e., projection mode is not "any"), and the
1553 // impl's type is declared as default, then we disable
1554 // projection (even if the trait ref is fully
1555 // monomorphic). In the case where trait ref is not
1556 // fully monomorphic (i.e., includes type parameters),
1557 // this is because those type parameters may
1558 // ultimately be bound to types from other crates that
1559 // may have specialized impls we can't see. In the
1560 // case where the trait ref IS fully monomorphic, this
1561 // is a policy decision that we made in the RFC in
1562 // order to preserve flexibility for the crate that
1563 // defined the specializable impl to specialize later
1564 // for existing types.
1566 // In either case, we handle this by not adding a
1567 // candidate for an impl if it contains a `default`
1570 // NOTE: This should be kept in sync with the similar code in
1571 // `rustc_ty_utils::instance::resolve_associated_item()`.
1573 assoc_def(selcx, impl_data.impl_def_id, obligation.predicate.item_def_id)
1574 .map_err(|ErrorGuaranteed { .. }| ())?;
1576 if node_item.is_final() {
1577 // Non-specializable items are always projectable.
1580 // Only reveal a specializable default if we're past type-checking
1581 // and the obligation is monomorphic, otherwise passes such as
1582 // transmute checking and polymorphic MIR optimizations could
1583 // get a result which isn't correct for all monomorphizations.
1584 if obligation.param_env.reveal() == Reveal::All {
1585 // NOTE(eddyb) inference variables can resolve to parameters, so
1586 // assume `poly_trait_ref` isn't monomorphic, if it contains any.
1587 let poly_trait_ref = selcx.infcx.resolve_vars_if_possible(poly_trait_ref);
1588 !poly_trait_ref.still_further_specializable()
1591 assoc_ty = ?selcx.tcx().def_path_str(node_item.item.def_id),
1592 ?obligation.predicate,
1593 "assemble_candidates_from_impls: not eligible due to default",
1599 super::ImplSource::Builtin(..) => {
1600 // While a builtin impl may be known to exist, the associated type may not yet
1601 // be known. Any type with multiple potential associated types is therefore
1603 let self_ty = selcx.infcx.shallow_resolve(obligation.predicate.self_ty());
1605 let lang_items = selcx.tcx().lang_items();
1606 if lang_items.discriminant_kind_trait() == Some(poly_trait_ref.def_id()) {
1607 match self_ty.kind() {
1625 | ty::GeneratorWitness(..)
1628 // Integers and floats always have `u8` as their discriminant.
1629 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(..)) => true,
1631 // type parameters, opaques, and unnormalized projections have pointer
1632 // metadata if they're known (e.g. by the param_env) to be sized
1634 | ty::Projection(..)
1637 | ty::Placeholder(..)
1639 | ty::Error(_) => false,
1641 } else if lang_items.pointee_trait() == Some(poly_trait_ref.def_id()) {
1642 let tail = selcx.tcx().struct_tail_with_normalize(
1645 // We throw away any obligations we get from this, since we normalize
1646 // and confirm these obligations once again during confirmation
1647 normalize_with_depth(
1649 obligation.param_env,
1650 obligation.cause.clone(),
1651 obligation.recursion_depth + 1,
1675 | ty::GeneratorWitness(..)
1677 // Extern types have unit metadata, according to RFC 2850
1679 // If returned by `struct_tail_without_normalization` this is a unit struct
1680 // without any fields, or not a struct, and therefore is Sized.
1682 // If returned by `struct_tail_without_normalization` this is the empty tuple.
1684 // Integers and floats are always Sized, and so have unit type metadata.
1685 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(..)) => true,
1687 // type parameters, opaques, and unnormalized projections have pointer
1688 // metadata if they're known (e.g. by the param_env) to be sized
1689 ty::Param(_) | ty::Projection(..) | ty::Opaque(..)
1690 if selcx.infcx.predicate_must_hold_modulo_regions(
1694 selcx.tcx().at(obligation.cause.span()).mk_trait_ref(LangItem::Sized, [self_ty]),
1703 // FIXME(compiler-errors): are Bound and Placeholder types ever known sized?
1705 | ty::Projection(..)
1708 | ty::Placeholder(..)
1711 if tail.has_infer_types() {
1712 candidate_set.mark_ambiguous();
1718 bug!("unexpected builtin trait with associated type: {poly_trait_ref:?}")
1721 super::ImplSource::Param(..) => {
1722 // This case tell us nothing about the value of an
1723 // associated type. Consider:
1726 // trait SomeTrait { type Foo; }
1727 // fn foo<T:SomeTrait>(...) { }
1730 // If the user writes `<T as SomeTrait>::Foo`, then the `T
1731 // : SomeTrait` binding does not help us decide what the
1732 // type `Foo` is (at least, not more specifically than
1733 // what we already knew).
1735 // But wait, you say! What about an example like this:
1738 // fn bar<T:SomeTrait<Foo=usize>>(...) { ... }
1741 // Doesn't the `T : SomeTrait<Foo=usize>` predicate help
1742 // resolve `T::Foo`? And of course it does, but in fact
1743 // that single predicate is desugared into two predicates
1744 // in the compiler: a trait predicate (`T : SomeTrait`) and a
1745 // projection. And the projection where clause is handled
1746 // in `assemble_candidates_from_param_env`.
1749 super::ImplSource::Object(_) => {
1750 // Handled by the `Object` projection candidate. See
1751 // `assemble_candidates_from_object_ty` for an explanation of
1752 // why we special case object types.
1755 super::ImplSource::AutoImpl(..)
1756 | super::ImplSource::TraitUpcasting(_)
1757 | super::ImplSource::ConstDestruct(_) => {
1758 // These traits have no associated types.
1759 selcx.tcx().sess.delay_span_bug(
1760 obligation.cause.span,
1761 &format!("Cannot project an associated type from `{:?}`", impl_source),
1768 if candidate_set.push_candidate(ProjectionCandidate::Select(impl_source)) {
1779 fn confirm_candidate<'cx, 'tcx>(
1780 selcx: &mut SelectionContext<'cx, 'tcx>,
1781 obligation: &ProjectionTyObligation<'tcx>,
1782 candidate: ProjectionCandidate<'tcx>,
1783 ) -> Progress<'tcx> {
1784 debug!(?obligation, ?candidate, "confirm_candidate");
1785 let mut progress = match candidate {
1786 ProjectionCandidate::ParamEnv(poly_projection)
1787 | ProjectionCandidate::Object(poly_projection) => {
1788 confirm_param_env_candidate(selcx, obligation, poly_projection, false)
1791 ProjectionCandidate::TraitDef(poly_projection) => {
1792 confirm_param_env_candidate(selcx, obligation, poly_projection, true)
1795 ProjectionCandidate::Select(impl_source) => {
1796 confirm_select_candidate(selcx, obligation, impl_source)
1798 ProjectionCandidate::ImplTraitInTrait(ImplTraitInTraitCandidate::Impl(data)) => {
1799 confirm_impl_trait_in_trait_candidate(selcx, obligation, data)
1801 // If we're projecting an RPITIT for a default trait body, that's just
1802 // the same def-id, but as an opaque type (with regular RPIT semantics).
1803 ProjectionCandidate::ImplTraitInTrait(ImplTraitInTraitCandidate::Trait) => Progress {
1806 .mk_opaque(obligation.predicate.item_def_id, obligation.predicate.substs)
1808 obligations: vec![],
1812 // When checking for cycle during evaluation, we compare predicates with
1813 // "syntactic" equality. Since normalization generally introduces a type
1814 // with new region variables, we need to resolve them to existing variables
1815 // when possible for this to work. See `auto-trait-projection-recursion.rs`
1816 // for a case where this matters.
1817 if progress.term.has_infer_regions() {
1818 progress.term = progress.term.fold_with(&mut OpportunisticRegionResolver::new(selcx.infcx));
1823 fn confirm_select_candidate<'cx, 'tcx>(
1824 selcx: &mut SelectionContext<'cx, 'tcx>,
1825 obligation: &ProjectionTyObligation<'tcx>,
1826 impl_source: Selection<'tcx>,
1827 ) -> Progress<'tcx> {
1829 super::ImplSource::UserDefined(data) => confirm_impl_candidate(selcx, obligation, data),
1830 super::ImplSource::Generator(data) => confirm_generator_candidate(selcx, obligation, data),
1831 super::ImplSource::Future(data) => confirm_future_candidate(selcx, obligation, data),
1832 super::ImplSource::Closure(data) => confirm_closure_candidate(selcx, obligation, data),
1833 super::ImplSource::FnPointer(data) => confirm_fn_pointer_candidate(selcx, obligation, data),
1834 super::ImplSource::Builtin(data) => confirm_builtin_candidate(selcx, obligation, data),
1835 super::ImplSource::Object(_)
1836 | super::ImplSource::AutoImpl(..)
1837 | super::ImplSource::Param(..)
1838 | super::ImplSource::TraitUpcasting(_)
1839 | super::ImplSource::TraitAlias(..)
1840 | super::ImplSource::ConstDestruct(_) => {
1841 // we don't create Select candidates with this kind of resolution
1843 obligation.cause.span,
1844 "Cannot project an associated type from `{:?}`",
1851 fn confirm_generator_candidate<'cx, 'tcx>(
1852 selcx: &mut SelectionContext<'cx, 'tcx>,
1853 obligation: &ProjectionTyObligation<'tcx>,
1854 impl_source: ImplSourceGeneratorData<'tcx, PredicateObligation<'tcx>>,
1855 ) -> Progress<'tcx> {
1856 let gen_sig = impl_source.substs.as_generator().poly_sig();
1857 let Normalized { value: gen_sig, obligations } = normalize_with_depth(
1859 obligation.param_env,
1860 obligation.cause.clone(),
1861 obligation.recursion_depth + 1,
1865 debug!(?obligation, ?gen_sig, ?obligations, "confirm_generator_candidate");
1867 let tcx = selcx.tcx();
1869 let gen_def_id = tcx.require_lang_item(LangItem::Generator, None);
1871 let predicate = super::util::generator_trait_ref_and_outputs(
1874 obligation.predicate.self_ty(),
1877 .map_bound(|(trait_ref, yield_ty, return_ty)| {
1878 let name = tcx.associated_item(obligation.predicate.item_def_id).name;
1879 let ty = if name == sym::Return {
1881 } else if name == sym::Yield {
1887 ty::ProjectionPredicate {
1888 projection_ty: ty::ProjectionTy {
1889 substs: trait_ref.substs,
1890 item_def_id: obligation.predicate.item_def_id,
1896 confirm_param_env_candidate(selcx, obligation, predicate, false)
1897 .with_addl_obligations(impl_source.nested)
1898 .with_addl_obligations(obligations)
1901 fn confirm_future_candidate<'cx, 'tcx>(
1902 selcx: &mut SelectionContext<'cx, 'tcx>,
1903 obligation: &ProjectionTyObligation<'tcx>,
1904 impl_source: ImplSourceFutureData<'tcx, PredicateObligation<'tcx>>,
1905 ) -> Progress<'tcx> {
1906 let gen_sig = impl_source.substs.as_generator().poly_sig();
1907 let Normalized { value: gen_sig, obligations } = normalize_with_depth(
1909 obligation.param_env,
1910 obligation.cause.clone(),
1911 obligation.recursion_depth + 1,
1915 debug!(?obligation, ?gen_sig, ?obligations, "confirm_future_candidate");
1917 let tcx = selcx.tcx();
1918 let fut_def_id = tcx.require_lang_item(LangItem::Future, None);
1920 let predicate = super::util::future_trait_ref_and_outputs(
1923 obligation.predicate.self_ty(),
1926 .map_bound(|(trait_ref, return_ty)| {
1927 debug_assert_eq!(tcx.associated_item(obligation.predicate.item_def_id).name, sym::Output);
1929 ty::ProjectionPredicate {
1930 projection_ty: ty::ProjectionTy {
1931 substs: trait_ref.substs,
1932 item_def_id: obligation.predicate.item_def_id,
1934 term: return_ty.into(),
1938 confirm_param_env_candidate(selcx, obligation, predicate, false)
1939 .with_addl_obligations(impl_source.nested)
1940 .with_addl_obligations(obligations)
1943 fn confirm_builtin_candidate<'cx, 'tcx>(
1944 selcx: &mut SelectionContext<'cx, 'tcx>,
1945 obligation: &ProjectionTyObligation<'tcx>,
1946 data: ImplSourceBuiltinData<PredicateObligation<'tcx>>,
1947 ) -> Progress<'tcx> {
1948 let tcx = selcx.tcx();
1949 let self_ty = obligation.predicate.self_ty();
1950 let substs = tcx.mk_substs([self_ty.into()].iter());
1951 let lang_items = tcx.lang_items();
1952 let item_def_id = obligation.predicate.item_def_id;
1953 let trait_def_id = tcx.trait_of_item(item_def_id).unwrap();
1954 let (term, obligations) = if lang_items.discriminant_kind_trait() == Some(trait_def_id) {
1955 let discriminant_def_id = tcx.require_lang_item(LangItem::Discriminant, None);
1956 assert_eq!(discriminant_def_id, item_def_id);
1958 (self_ty.discriminant_ty(tcx).into(), Vec::new())
1959 } else if lang_items.pointee_trait() == Some(trait_def_id) {
1960 let metadata_def_id = tcx.require_lang_item(LangItem::Metadata, None);
1961 assert_eq!(metadata_def_id, item_def_id);
1963 let mut obligations = Vec::new();
1964 let (metadata_ty, check_is_sized) = self_ty.ptr_metadata_ty(tcx, |ty| {
1965 normalize_with_depth_to(
1967 obligation.param_env,
1968 obligation.cause.clone(),
1969 obligation.recursion_depth + 1,
1975 let sized_predicate = ty::Binder::dummy(
1976 tcx.at(obligation.cause.span()).mk_trait_ref(LangItem::Sized, [self_ty]),
1979 obligations.push(obligation.with(tcx, sized_predicate));
1981 (metadata_ty.into(), obligations)
1983 bug!("unexpected builtin trait with associated type: {:?}", obligation.predicate);
1987 ty::ProjectionPredicate { projection_ty: ty::ProjectionTy { substs, item_def_id }, term };
1989 confirm_param_env_candidate(selcx, obligation, ty::Binder::dummy(predicate), false)
1990 .with_addl_obligations(obligations)
1991 .with_addl_obligations(data.nested)
1994 fn confirm_fn_pointer_candidate<'cx, 'tcx>(
1995 selcx: &mut SelectionContext<'cx, 'tcx>,
1996 obligation: &ProjectionTyObligation<'tcx>,
1997 fn_pointer_impl_source: ImplSourceFnPointerData<'tcx, PredicateObligation<'tcx>>,
1998 ) -> Progress<'tcx> {
1999 let fn_type = selcx.infcx.shallow_resolve(fn_pointer_impl_source.fn_ty);
2000 let sig = fn_type.fn_sig(selcx.tcx());
2001 let Normalized { value: sig, obligations } = normalize_with_depth(
2003 obligation.param_env,
2004 obligation.cause.clone(),
2005 obligation.recursion_depth + 1,
2009 confirm_callable_candidate(selcx, obligation, sig, util::TupleArgumentsFlag::Yes)
2010 .with_addl_obligations(fn_pointer_impl_source.nested)
2011 .with_addl_obligations(obligations)
2014 fn confirm_closure_candidate<'cx, 'tcx>(
2015 selcx: &mut SelectionContext<'cx, 'tcx>,
2016 obligation: &ProjectionTyObligation<'tcx>,
2017 impl_source: ImplSourceClosureData<'tcx, PredicateObligation<'tcx>>,
2018 ) -> Progress<'tcx> {
2019 let closure_sig = impl_source.substs.as_closure().sig();
2020 let Normalized { value: closure_sig, obligations } = normalize_with_depth(
2022 obligation.param_env,
2023 obligation.cause.clone(),
2024 obligation.recursion_depth + 1,
2028 debug!(?obligation, ?closure_sig, ?obligations, "confirm_closure_candidate");
2030 confirm_callable_candidate(selcx, obligation, closure_sig, util::TupleArgumentsFlag::No)
2031 .with_addl_obligations(impl_source.nested)
2032 .with_addl_obligations(obligations)
2035 fn confirm_callable_candidate<'cx, 'tcx>(
2036 selcx: &mut SelectionContext<'cx, 'tcx>,
2037 obligation: &ProjectionTyObligation<'tcx>,
2038 fn_sig: ty::PolyFnSig<'tcx>,
2039 flag: util::TupleArgumentsFlag,
2040 ) -> Progress<'tcx> {
2041 let tcx = selcx.tcx();
2043 debug!(?obligation, ?fn_sig, "confirm_callable_candidate");
2045 let fn_once_def_id = tcx.require_lang_item(LangItem::FnOnce, None);
2046 let fn_once_output_def_id = tcx.require_lang_item(LangItem::FnOnceOutput, None);
2048 let predicate = super::util::closure_trait_ref_and_return_type(
2051 obligation.predicate.self_ty(),
2055 .map_bound(|(trait_ref, ret_type)| ty::ProjectionPredicate {
2056 projection_ty: ty::ProjectionTy {
2057 substs: trait_ref.substs,
2058 item_def_id: fn_once_output_def_id,
2060 term: ret_type.into(),
2063 confirm_param_env_candidate(selcx, obligation, predicate, true)
2066 fn confirm_param_env_candidate<'cx, 'tcx>(
2067 selcx: &mut SelectionContext<'cx, 'tcx>,
2068 obligation: &ProjectionTyObligation<'tcx>,
2069 poly_cache_entry: ty::PolyProjectionPredicate<'tcx>,
2070 potentially_unnormalized_candidate: bool,
2071 ) -> Progress<'tcx> {
2072 let infcx = selcx.infcx;
2073 let cause = &obligation.cause;
2074 let param_env = obligation.param_env;
2076 let cache_entry = infcx.replace_bound_vars_with_fresh_vars(
2078 LateBoundRegionConversionTime::HigherRankedType,
2082 let cache_projection = cache_entry.projection_ty;
2083 let mut nested_obligations = Vec::new();
2084 let obligation_projection = obligation.predicate;
2085 let obligation_projection = ensure_sufficient_stack(|| {
2086 normalize_with_depth_to(
2088 obligation.param_env,
2089 obligation.cause.clone(),
2090 obligation.recursion_depth + 1,
2091 obligation_projection,
2092 &mut nested_obligations,
2095 let cache_projection = if potentially_unnormalized_candidate {
2096 ensure_sufficient_stack(|| {
2097 normalize_with_depth_to(
2099 obligation.param_env,
2100 obligation.cause.clone(),
2101 obligation.recursion_depth + 1,
2103 &mut nested_obligations,
2110 debug!(?cache_projection, ?obligation_projection);
2112 match infcx.at(cause, param_env).eq(cache_projection, obligation_projection) {
2113 Ok(InferOk { value: _, obligations }) => {
2114 nested_obligations.extend(obligations);
2115 assoc_ty_own_obligations(selcx, obligation, &mut nested_obligations);
2116 // FIXME(associated_const_equality): Handle consts here as well? Maybe this progress type should just take
2118 Progress { term: cache_entry.term, obligations: nested_obligations }
2122 "Failed to unify obligation `{:?}` with poly_projection `{:?}`: {:?}",
2123 obligation, poly_cache_entry, e,
2125 debug!("confirm_param_env_candidate: {}", msg);
2126 let err = infcx.tcx.ty_error_with_message(obligation.cause.span, &msg);
2127 Progress { term: err.into(), obligations: vec![] }
2132 fn confirm_impl_candidate<'cx, 'tcx>(
2133 selcx: &mut SelectionContext<'cx, 'tcx>,
2134 obligation: &ProjectionTyObligation<'tcx>,
2135 impl_impl_source: ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>>,
2136 ) -> Progress<'tcx> {
2137 let tcx = selcx.tcx();
2139 let ImplSourceUserDefinedData { impl_def_id, substs, mut nested } = impl_impl_source;
2140 let assoc_item_id = obligation.predicate.item_def_id;
2141 let trait_def_id = tcx.trait_id_of_impl(impl_def_id).unwrap();
2143 let param_env = obligation.param_env;
2144 let Ok(assoc_ty) = assoc_def(selcx, impl_def_id, assoc_item_id) else {
2145 return Progress { term: tcx.ty_error().into(), obligations: nested };
2148 if !assoc_ty.item.defaultness(tcx).has_value() {
2149 // This means that the impl is missing a definition for the
2150 // associated type. This error will be reported by the type
2151 // checker method `check_impl_items_against_trait`, so here we
2152 // just return Error.
2154 "confirm_impl_candidate: no associated type {:?} for {:?}",
2155 assoc_ty.item.name, obligation.predicate
2157 return Progress { term: tcx.ty_error().into(), obligations: nested };
2159 // If we're trying to normalize `<Vec<u32> as X>::A<S>` using
2160 //`impl<T> X for Vec<T> { type A<Y> = Box<Y>; }`, then:
2162 // * `obligation.predicate.substs` is `[Vec<u32>, S]`
2163 // * `substs` is `[u32]`
2164 // * `substs` ends up as `[u32, S]`
2165 let substs = obligation.predicate.substs.rebase_onto(tcx, trait_def_id, substs);
2167 translate_substs(selcx.infcx, param_env, impl_def_id, substs, assoc_ty.defining_node);
2168 let ty = tcx.bound_type_of(assoc_ty.item.def_id);
2169 let is_const = matches!(tcx.def_kind(assoc_ty.item.def_id), DefKind::AssocConst);
2170 let term: ty::EarlyBinder<ty::Term<'tcx>> = if is_const {
2171 let identity_substs =
2172 crate::traits::InternalSubsts::identity_for_item(tcx, assoc_ty.item.def_id);
2173 let did = ty::WithOptConstParam::unknown(assoc_ty.item.def_id);
2174 let kind = ty::ConstKind::Unevaluated(ty::UnevaluatedConst::new(did, identity_substs));
2175 ty.map_bound(|ty| tcx.mk_const(kind, ty).into())
2177 ty.map_bound(|ty| ty.into())
2179 if !check_substs_compatible(tcx, &assoc_ty.item, substs) {
2180 let err = tcx.ty_error_with_message(
2181 obligation.cause.span,
2182 "impl item and trait item have different parameters",
2184 Progress { term: err.into(), obligations: nested }
2186 assoc_ty_own_obligations(selcx, obligation, &mut nested);
2187 Progress { term: term.subst(tcx, substs), obligations: nested }
2191 // Verify that the trait item and its implementation have compatible substs lists
2192 fn check_substs_compatible<'tcx>(
2194 assoc_item: &ty::AssocItem,
2195 substs: ty::SubstsRef<'tcx>,
2197 fn check_substs_compatible_inner<'tcx>(
2199 generics: &'tcx ty::Generics,
2200 args: &'tcx [ty::GenericArg<'tcx>],
2202 if generics.count() != args.len() {
2206 let (parent_args, own_args) = args.split_at(generics.parent_count);
2208 if let Some(parent) = generics.parent
2209 && let parent_generics = tcx.generics_of(parent)
2210 && !check_substs_compatible_inner(tcx, parent_generics, parent_args) {
2214 for (param, arg) in std::iter::zip(&generics.params, own_args) {
2215 match (¶m.kind, arg.unpack()) {
2216 (ty::GenericParamDefKind::Type { .. }, ty::GenericArgKind::Type(_))
2217 | (ty::GenericParamDefKind::Lifetime, ty::GenericArgKind::Lifetime(_))
2218 | (ty::GenericParamDefKind::Const { .. }, ty::GenericArgKind::Const(_)) => {}
2226 let generics = tcx.generics_of(assoc_item.def_id);
2227 // Chop off any additional substs (RPITIT) substs
2228 let substs = &substs[0..generics.count().min(substs.len())];
2229 check_substs_compatible_inner(tcx, generics, substs)
2232 fn confirm_impl_trait_in_trait_candidate<'tcx>(
2233 selcx: &mut SelectionContext<'_, 'tcx>,
2234 obligation: &ProjectionTyObligation<'tcx>,
2235 data: ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>>,
2236 ) -> Progress<'tcx> {
2237 let tcx = selcx.tcx();
2238 let mut obligations = data.nested;
2240 let trait_fn_def_id = tcx.impl_trait_in_trait_parent(obligation.predicate.item_def_id);
2241 let Ok(leaf_def) = assoc_def(selcx, data.impl_def_id, trait_fn_def_id) else {
2242 return Progress { term: tcx.ty_error().into(), obligations };
2244 if !leaf_def.item.defaultness(tcx).has_value() {
2245 return Progress { term: tcx.ty_error().into(), obligations };
2248 // Use the default `impl Trait` for the trait, e.g., for a default trait body
2249 if leaf_def.item.container == ty::AssocItemContainer::TraitContainer {
2252 .mk_opaque(obligation.predicate.item_def_id, obligation.predicate.substs)
2258 // Rebase from {trait}::{fn}::{opaque} to {impl}::{fn}::{opaque},
2259 // since `data.substs` are the impl substs.
2260 let impl_fn_substs =
2261 obligation.predicate.substs.rebase_onto(tcx, tcx.parent(trait_fn_def_id), data.substs);
2262 let impl_fn_substs = translate_substs(
2264 obligation.param_env,
2267 leaf_def.defining_node,
2270 if !check_substs_compatible(tcx, &leaf_def.item, impl_fn_substs) {
2271 let err = tcx.ty_error_with_message(
2272 obligation.cause.span,
2273 "impl method and trait method have different parameters",
2275 return Progress { term: err.into(), obligations };
2278 let impl_fn_def_id = leaf_def.item.def_id;
2280 let cause = ObligationCause::new(
2281 obligation.cause.span,
2282 obligation.cause.body_id,
2283 super::ItemObligation(impl_fn_def_id),
2285 let predicates = normalize_with_depth_to(
2287 obligation.param_env,
2289 obligation.recursion_depth + 1,
2290 tcx.predicates_of(impl_fn_def_id).instantiate(tcx, impl_fn_substs),
2293 obligations.extend(std::iter::zip(predicates.predicates, predicates.spans).map(
2295 Obligation::with_depth(
2297 ObligationCause::new(
2298 obligation.cause.span,
2299 obligation.cause.body_id,
2300 if span.is_dummy() {
2301 super::ItemObligation(impl_fn_def_id)
2303 super::BindingObligation(impl_fn_def_id, span)
2306 obligation.recursion_depth + 1,
2307 obligation.param_env,
2313 let ty = super::normalize_to(
2315 obligation.param_env,
2317 tcx.bound_trait_impl_trait_tys(impl_fn_def_id)
2319 tys.map_or_else(|_| tcx.ty_error(), |tys| tys[&obligation.predicate.item_def_id])
2321 .subst(tcx, impl_fn_substs),
2325 Progress { term: ty.into(), obligations }
2328 // Get obligations corresponding to the predicates from the where-clause of the
2329 // associated type itself.
2330 fn assoc_ty_own_obligations<'cx, 'tcx>(
2331 selcx: &mut SelectionContext<'cx, 'tcx>,
2332 obligation: &ProjectionTyObligation<'tcx>,
2333 nested: &mut Vec<PredicateObligation<'tcx>>,
2335 let tcx = selcx.tcx();
2336 for predicate in tcx
2337 .predicates_of(obligation.predicate.item_def_id)
2338 .instantiate_own(tcx, obligation.predicate.substs)
2341 let normalized = normalize_with_depth_to(
2343 obligation.param_env,
2344 obligation.cause.clone(),
2345 obligation.recursion_depth + 1,
2349 nested.push(Obligation::with_depth(
2351 obligation.cause.clone(),
2352 obligation.recursion_depth + 1,
2353 obligation.param_env,
2359 /// Locate the definition of an associated type in the specialization hierarchy,
2360 /// starting from the given impl.
2362 /// Based on the "projection mode", this lookup may in fact only examine the
2363 /// topmost impl. See the comments for `Reveal` for more details.
2365 selcx: &SelectionContext<'_, '_>,
2367 assoc_def_id: DefId,
2368 ) -> Result<specialization_graph::LeafDef, ErrorGuaranteed> {
2369 let tcx = selcx.tcx();
2370 let trait_def_id = tcx.impl_trait_ref(impl_def_id).unwrap().def_id;
2371 let trait_def = tcx.trait_def(trait_def_id);
2373 // This function may be called while we are still building the
2374 // specialization graph that is queried below (via TraitDef::ancestors()),
2375 // so, in order to avoid unnecessary infinite recursion, we manually look
2376 // for the associated item at the given impl.
2377 // If there is no such item in that impl, this function will fail with a
2378 // cycle error if the specialization graph is currently being built.
2379 if let Some(&impl_item_id) = tcx.impl_item_implementor_ids(impl_def_id).get(&assoc_def_id) {
2380 let item = tcx.associated_item(impl_item_id);
2381 let impl_node = specialization_graph::Node::Impl(impl_def_id);
2382 return Ok(specialization_graph::LeafDef {
2384 defining_node: impl_node,
2385 finalizing_node: if item.defaultness(tcx).is_default() {
2393 let ancestors = trait_def.ancestors(tcx, impl_def_id)?;
2394 if let Some(assoc_item) = ancestors.leaf_def(tcx, assoc_def_id) {
2397 // This is saying that neither the trait nor
2398 // the impl contain a definition for this
2399 // associated type. Normally this situation
2400 // could only arise through a compiler bug --
2401 // if the user wrote a bad item name, it
2402 // should have failed in astconv.
2404 "No associated type `{}` for {}",
2405 tcx.item_name(assoc_def_id),
2406 tcx.def_path_str(impl_def_id)
2411 pub(crate) trait ProjectionCacheKeyExt<'cx, 'tcx>: Sized {
2412 fn from_poly_projection_predicate(
2413 selcx: &mut SelectionContext<'cx, 'tcx>,
2414 predicate: ty::PolyProjectionPredicate<'tcx>,
2418 impl<'cx, 'tcx> ProjectionCacheKeyExt<'cx, 'tcx> for ProjectionCacheKey<'tcx> {
2419 fn from_poly_projection_predicate(
2420 selcx: &mut SelectionContext<'cx, 'tcx>,
2421 predicate: ty::PolyProjectionPredicate<'tcx>,
2423 let infcx = selcx.infcx;
2424 // We don't do cross-snapshot caching of obligations with escaping regions,
2425 // so there's no cache key to use
2426 predicate.no_bound_vars().map(|predicate| {
2427 ProjectionCacheKey::new(
2428 // We don't attempt to match up with a specific type-variable state
2429 // from a specific call to `opt_normalize_projection_type` - if
2430 // there's no precise match, the original cache entry is "stranded"
2432 infcx.resolve_vars_if_possible(predicate.projection_ty),