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 fn normalize<T: TypeFoldable<'tcx>>(&self, t: T) -> InferOk<'tcx, T>;
56 impl<'tcx> NormalizeExt<'tcx> for At<'_, 'tcx> {
57 fn normalize<T: TypeFoldable<'tcx>>(&self, value: T) -> InferOk<'tcx, T> {
58 let mut selcx = SelectionContext::new(self.infcx);
59 let Normalized { value, obligations } =
60 normalize(&mut selcx, self.param_env, self.cause.clone(), value);
61 InferOk { value, obligations }
65 /// When attempting to resolve `<T as TraitRef>::Name` ...
67 pub enum ProjectionError<'tcx> {
68 /// ...we found multiple sources of information and couldn't resolve the ambiguity.
71 /// ...an error occurred matching `T : TraitRef`
72 TraitSelectionError(SelectionError<'tcx>),
75 #[derive(PartialEq, Eq, Debug)]
76 enum ProjectionCandidate<'tcx> {
77 /// From a where-clause in the env or object type
78 ParamEnv(ty::PolyProjectionPredicate<'tcx>),
80 /// From the definition of `Trait` when you have something like
81 /// `<<A as Trait>::B as Trait2>::C`.
82 TraitDef(ty::PolyProjectionPredicate<'tcx>),
84 /// Bounds specified on an object type
85 Object(ty::PolyProjectionPredicate<'tcx>),
87 /// From an "impl" (or a "pseudo-impl" returned by select)
88 Select(Selection<'tcx>),
90 ImplTraitInTrait(ImplTraitInTraitCandidate<'tcx>),
93 #[derive(PartialEq, Eq, Debug)]
94 enum ImplTraitInTraitCandidate<'tcx> {
95 // The `impl Trait` from a trait function's default body
97 // A concrete type provided from a trait's `impl Trait` from an impl
98 Impl(ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>>),
101 enum ProjectionCandidateSet<'tcx> {
103 Single(ProjectionCandidate<'tcx>),
105 Error(SelectionError<'tcx>),
108 impl<'tcx> ProjectionCandidateSet<'tcx> {
109 fn mark_ambiguous(&mut self) {
110 *self = ProjectionCandidateSet::Ambiguous;
113 fn mark_error(&mut self, err: SelectionError<'tcx>) {
114 *self = ProjectionCandidateSet::Error(err);
117 // Returns true if the push was successful, or false if the candidate
118 // was discarded -- this could be because of ambiguity, or because
119 // a higher-priority candidate is already there.
120 fn push_candidate(&mut self, candidate: ProjectionCandidate<'tcx>) -> bool {
121 use self::ProjectionCandidate::*;
122 use self::ProjectionCandidateSet::*;
124 // This wacky variable is just used to try and
125 // make code readable and avoid confusing paths.
126 // It is assigned a "value" of `()` only on those
127 // paths in which we wish to convert `*self` to
128 // ambiguous (and return false, because the candidate
129 // was not used). On other paths, it is not assigned,
130 // and hence if those paths *could* reach the code that
131 // comes after the match, this fn would not compile.
132 let convert_to_ambiguous;
136 *self = Single(candidate);
141 // Duplicates can happen inside ParamEnv. In the case, we
142 // perform a lazy deduplication.
143 if current == &candidate {
147 // Prefer where-clauses. As in select, if there are multiple
148 // candidates, we prefer where-clause candidates over impls. This
149 // may seem a bit surprising, since impls are the source of
150 // "truth" in some sense, but in fact some of the impls that SEEM
151 // applicable are not, because of nested obligations. Where
152 // clauses are the safer choice. See the comment on
153 // `select::SelectionCandidate` and #21974 for more details.
154 match (current, candidate) {
155 (ParamEnv(..), ParamEnv(..)) => convert_to_ambiguous = (),
156 (ParamEnv(..), _) => return false,
157 (_, ParamEnv(..)) => unreachable!(),
158 (_, _) => convert_to_ambiguous = (),
162 Ambiguous | Error(..) => {
167 // We only ever get here when we moved from a single candidate
169 let () = convert_to_ambiguous;
175 /// States returned from `poly_project_and_unify_type`. Takes the place
176 /// of the old return type, which was:
177 /// ```ignore (not-rust)
179 /// Result<Option<Vec<PredicateObligation<'tcx>>>, InProgress>,
180 /// MismatchedProjectionTypes<'tcx>,
183 pub(super) enum ProjectAndUnifyResult<'tcx> {
184 /// The projection bound holds subject to the given obligations. If the
185 /// projection cannot be normalized because the required trait bound does
186 /// not hold, this is returned, with `obligations` being a predicate that
187 /// cannot be proven.
188 Holds(Vec<PredicateObligation<'tcx>>),
189 /// The projection cannot be normalized due to ambiguity. Resolving some
190 /// inference variables in the projection may fix this.
192 /// The project cannot be normalized because `poly_project_and_unify_type`
193 /// is called recursively while normalizing the same projection.
195 // the projection can be normalized, but is not equal to the expected type.
196 // Returns the type error that arose from the mismatch.
197 MismatchedProjectionTypes(MismatchedProjectionTypes<'tcx>),
200 /// Evaluates constraints of the form:
201 /// ```ignore (not-rust)
202 /// for<...> <T as Trait>::U == V
204 /// If successful, this may result in additional obligations. Also returns
205 /// the projection cache key used to track these additional obligations.
206 #[instrument(level = "debug", skip(selcx))]
207 pub(super) fn poly_project_and_unify_type<'cx, 'tcx>(
208 selcx: &mut SelectionContext<'cx, 'tcx>,
209 obligation: &PolyProjectionObligation<'tcx>,
210 ) -> ProjectAndUnifyResult<'tcx> {
211 let infcx = selcx.infcx;
212 let r = infcx.commit_if_ok(|_snapshot| {
213 let old_universe = infcx.universe();
214 let placeholder_predicate =
215 infcx.replace_bound_vars_with_placeholders(obligation.predicate);
216 let new_universe = infcx.universe();
218 let placeholder_obligation = obligation.with(infcx.tcx, placeholder_predicate);
219 match project_and_unify_type(selcx, &placeholder_obligation) {
220 ProjectAndUnifyResult::MismatchedProjectionTypes(e) => Err(e),
221 ProjectAndUnifyResult::Holds(obligations)
222 if old_universe != new_universe
223 && selcx.tcx().features().generic_associated_types_extended =>
225 // If the `generic_associated_types_extended` feature is active, then we ignore any
226 // obligations references lifetimes from any universe greater than or equal to the
227 // universe just created. Otherwise, we can end up with something like `for<'a> I: 'a`,
228 // which isn't quite what we want. Ideally, we want either an implied
229 // `for<'a where I: 'a> I: 'a` or we want to "lazily" check these hold when we
230 // substitute concrete regions. There is design work to be done here; until then,
231 // however, this allows experimenting potential GAT features without running into
232 // well-formedness issues.
233 let new_obligations = obligations
235 .filter(|obligation| {
236 let mut visitor = MaxUniverse::new();
237 obligation.predicate.visit_with(&mut visitor);
238 visitor.max_universe() < new_universe
241 Ok(ProjectAndUnifyResult::Holds(new_obligations))
249 Err(err) => ProjectAndUnifyResult::MismatchedProjectionTypes(err),
253 /// Evaluates constraints of the form:
254 /// ```ignore (not-rust)
255 /// <T as Trait>::U == V
257 /// If successful, this may result in additional obligations.
259 /// See [poly_project_and_unify_type] for an explanation of the return value.
260 #[instrument(level = "debug", skip(selcx))]
261 fn project_and_unify_type<'cx, 'tcx>(
262 selcx: &mut SelectionContext<'cx, 'tcx>,
263 obligation: &ProjectionObligation<'tcx>,
264 ) -> ProjectAndUnifyResult<'tcx> {
265 let mut obligations = vec![];
267 let infcx = selcx.infcx;
268 let normalized = match opt_normalize_projection_type(
270 obligation.param_env,
271 obligation.predicate.projection_ty,
272 obligation.cause.clone(),
273 obligation.recursion_depth,
277 Ok(None) => return ProjectAndUnifyResult::FailedNormalization,
278 Err(InProgress) => return ProjectAndUnifyResult::Recursive,
280 debug!(?normalized, ?obligations, "project_and_unify_type result");
281 let actual = obligation.predicate.term;
282 // For an example where this is necessary see src/test/ui/impl-trait/nested-return-type2.rs
283 // This allows users to omit re-mentioning all bounds on an associated type and just use an
284 // `impl Trait` for the assoc type to add more bounds.
285 let InferOk { value: actual, obligations: new } =
286 selcx.infcx.replace_opaque_types_with_inference_vars(
288 obligation.cause.body_id,
289 obligation.cause.span,
290 obligation.param_env,
292 obligations.extend(new);
294 match infcx.at(&obligation.cause, obligation.param_env).eq(normalized, actual) {
295 Ok(InferOk { obligations: inferred_obligations, value: () }) => {
296 obligations.extend(inferred_obligations);
297 ProjectAndUnifyResult::Holds(obligations)
300 debug!("equating types encountered error {:?}", err);
301 ProjectAndUnifyResult::MismatchedProjectionTypes(MismatchedProjectionTypes { err })
306 /// Normalizes any associated type projections in `value`, replacing
307 /// them with a fully resolved type where possible. The return value
308 /// combines the normalized result and any additional obligations that
309 /// were incurred as result.
310 pub(crate) fn normalize<'a, 'b, 'tcx, T>(
311 selcx: &'a mut SelectionContext<'b, 'tcx>,
312 param_env: ty::ParamEnv<'tcx>,
313 cause: ObligationCause<'tcx>,
315 ) -> Normalized<'tcx, T>
317 T: TypeFoldable<'tcx>,
319 let mut obligations = Vec::new();
320 let value = normalize_to(selcx, param_env, cause, value, &mut obligations);
321 Normalized { value, obligations }
324 pub(crate) fn normalize_to<'a, 'b, 'tcx, T>(
325 selcx: &'a mut SelectionContext<'b, 'tcx>,
326 param_env: ty::ParamEnv<'tcx>,
327 cause: ObligationCause<'tcx>,
329 obligations: &mut Vec<PredicateObligation<'tcx>>,
332 T: TypeFoldable<'tcx>,
334 normalize_with_depth_to(selcx, param_env, cause, 0, value, obligations)
337 /// As `normalize`, but with a custom depth.
338 pub(crate) fn normalize_with_depth<'a, 'b, 'tcx, T>(
339 selcx: &'a mut SelectionContext<'b, 'tcx>,
340 param_env: ty::ParamEnv<'tcx>,
341 cause: ObligationCause<'tcx>,
344 ) -> Normalized<'tcx, T>
346 T: TypeFoldable<'tcx>,
348 let mut obligations = Vec::new();
349 let value = normalize_with_depth_to(selcx, param_env, cause, depth, value, &mut obligations);
350 Normalized { value, obligations }
353 #[instrument(level = "info", skip(selcx, param_env, cause, obligations))]
354 pub(crate) fn normalize_with_depth_to<'a, 'b, 'tcx, T>(
355 selcx: &'a mut SelectionContext<'b, 'tcx>,
356 param_env: ty::ParamEnv<'tcx>,
357 cause: ObligationCause<'tcx>,
360 obligations: &mut Vec<PredicateObligation<'tcx>>,
363 T: TypeFoldable<'tcx>,
365 debug!(obligations.len = obligations.len());
366 let mut normalizer = AssocTypeNormalizer::new(selcx, param_env, cause, depth, obligations);
367 let result = ensure_sufficient_stack(|| normalizer.fold(value));
368 debug!(?result, obligations.len = normalizer.obligations.len());
369 debug!(?normalizer.obligations,);
373 #[instrument(level = "info", skip(selcx, param_env, cause, obligations))]
374 pub(crate) fn try_normalize_with_depth_to<'a, 'b, 'tcx, T>(
375 selcx: &'a mut SelectionContext<'b, 'tcx>,
376 param_env: ty::ParamEnv<'tcx>,
377 cause: ObligationCause<'tcx>,
380 obligations: &mut Vec<PredicateObligation<'tcx>>,
383 T: TypeFoldable<'tcx>,
385 debug!(obligations.len = obligations.len());
386 let mut normalizer = AssocTypeNormalizer::new_without_eager_inference_replacement(
393 let result = ensure_sufficient_stack(|| normalizer.fold(value));
394 debug!(?result, obligations.len = normalizer.obligations.len());
395 debug!(?normalizer.obligations,);
399 pub(crate) fn needs_normalization<'tcx, T: TypeVisitable<'tcx>>(value: &T, reveal: Reveal) -> bool {
401 Reveal::UserFacing => value
402 .has_type_flags(ty::TypeFlags::HAS_TY_PROJECTION | ty::TypeFlags::HAS_CT_PROJECTION),
403 Reveal::All => value.has_type_flags(
404 ty::TypeFlags::HAS_TY_PROJECTION
405 | ty::TypeFlags::HAS_TY_OPAQUE
406 | ty::TypeFlags::HAS_CT_PROJECTION,
411 struct AssocTypeNormalizer<'a, 'b, 'tcx> {
412 selcx: &'a mut SelectionContext<'b, 'tcx>,
413 param_env: ty::ParamEnv<'tcx>,
414 cause: ObligationCause<'tcx>,
415 obligations: &'a mut Vec<PredicateObligation<'tcx>>,
417 universes: Vec<Option<ty::UniverseIndex>>,
418 /// If true, when a projection is unable to be completed, an inference
419 /// variable will be created and an obligation registered to project to that
420 /// inference variable. Also, constants will be eagerly evaluated.
421 eager_inference_replacement: bool,
424 impl<'a, 'b, 'tcx> AssocTypeNormalizer<'a, 'b, 'tcx> {
426 selcx: &'a mut SelectionContext<'b, 'tcx>,
427 param_env: ty::ParamEnv<'tcx>,
428 cause: ObligationCause<'tcx>,
430 obligations: &'a mut Vec<PredicateObligation<'tcx>>,
431 ) -> AssocTypeNormalizer<'a, 'b, 'tcx> {
432 AssocTypeNormalizer {
439 eager_inference_replacement: true,
443 fn new_without_eager_inference_replacement(
444 selcx: &'a mut SelectionContext<'b, 'tcx>,
445 param_env: ty::ParamEnv<'tcx>,
446 cause: ObligationCause<'tcx>,
448 obligations: &'a mut Vec<PredicateObligation<'tcx>>,
449 ) -> AssocTypeNormalizer<'a, 'b, 'tcx> {
450 AssocTypeNormalizer {
457 eager_inference_replacement: false,
461 fn fold<T: TypeFoldable<'tcx>>(&mut self, value: T) -> T {
462 let value = self.selcx.infcx.resolve_vars_if_possible(value);
466 !value.has_escaping_bound_vars(),
467 "Normalizing {:?} without wrapping in a `Binder`",
471 if !needs_normalization(&value, self.param_env.reveal()) {
474 value.fold_with(self)
479 impl<'a, 'b, 'tcx> TypeFolder<'tcx> for AssocTypeNormalizer<'a, 'b, 'tcx> {
480 fn tcx<'c>(&'c self) -> TyCtxt<'tcx> {
484 fn fold_binder<T: TypeFoldable<'tcx>>(
486 t: ty::Binder<'tcx, T>,
487 ) -> ty::Binder<'tcx, T> {
488 self.universes.push(None);
489 let t = t.super_fold_with(self);
490 self.universes.pop();
494 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
495 if !needs_normalization(&ty, self.param_env.reveal()) {
499 // We try to be a little clever here as a performance optimization in
500 // cases where there are nested projections under binders.
503 // for<'a> fn(<T as Foo>::One<'a, Box<dyn Bar<'a, Item=<T as Foo>::Two<'a>>>>)
505 // We normalize the substs on the projection before the projecting, but
506 // if we're naive, we'll
507 // replace bound vars on inner, project inner, replace placeholders on inner,
508 // replace bound vars on outer, project outer, replace placeholders on outer
510 // However, if we're a bit more clever, we can replace the bound vars
511 // on the entire type before normalizing nested projections, meaning we
512 // replace bound vars on outer, project inner,
513 // project outer, replace placeholders on outer
515 // This is possible because the inner `'a` will already be a placeholder
516 // when we need to normalize the inner projection
518 // On the other hand, this does add a bit of complexity, since we only
519 // replace bound vars if the current type is a `Projection` and we need
520 // to make sure we don't forget to fold the substs regardless.
523 // This is really important. While we *can* handle this, this has
524 // severe performance implications for large opaque types with
525 // late-bound regions. See `issue-88862` benchmark.
526 ty::Opaque(def_id, substs) if !substs.has_escaping_bound_vars() => {
527 // Only normalize `impl Trait` outside of type inference, usually in codegen.
528 match self.param_env.reveal() {
529 Reveal::UserFacing => ty.super_fold_with(self),
532 let recursion_limit = self.tcx().recursion_limit();
533 if !recursion_limit.value_within_limit(self.depth) {
534 let obligation = Obligation::with_depth(
541 self.selcx.infcx.err_ctxt().report_overflow_error(&obligation, true);
544 let substs = substs.fold_with(self);
545 let generic_ty = self.tcx().bound_type_of(def_id);
546 let concrete_ty = generic_ty.subst(self.tcx(), substs);
548 let folded_ty = self.fold_ty(concrete_ty);
555 ty::Projection(data) if !data.has_escaping_bound_vars() => {
556 // This branch is *mostly* just an optimization: when we don't
557 // have escaping bound vars, we don't need to replace them with
558 // placeholders (see branch below). *Also*, we know that we can
559 // register an obligation to *later* project, since we know
560 // there won't be bound vars there.
561 let data = data.fold_with(self);
562 let normalized_ty = if self.eager_inference_replacement {
563 normalize_projection_type(
569 &mut self.obligations,
572 opt_normalize_projection_type(
578 &mut self.obligations,
582 .unwrap_or_else(|| ty.super_fold_with(self).into())
588 obligations.len = ?self.obligations.len(),
589 "AssocTypeNormalizer: normalized type"
591 normalized_ty.ty().unwrap()
594 ty::Projection(data) => {
595 // If there are escaping bound vars, we temporarily replace the
596 // bound vars with placeholders. Note though, that in the case
597 // that we still can't project for whatever reason (e.g. self
598 // type isn't known enough), we *can't* register an obligation
599 // and return an inference variable (since then that obligation
600 // would have bound vars and that's a can of worms). Instead,
601 // we just give up and fall back to pretending like we never tried!
603 // Note: this isn't necessarily the final approach here; we may
604 // want to figure out how to register obligations with escaping vars
605 // or handle this some other way.
607 let infcx = self.selcx.infcx;
608 let (data, mapped_regions, mapped_types, mapped_consts) =
609 BoundVarReplacer::replace_bound_vars(infcx, &mut self.universes, data);
610 let data = data.fold_with(self);
611 let normalized_ty = opt_normalize_projection_type(
617 &mut self.obligations,
621 .map(|term| term.ty().unwrap())
622 .map(|normalized_ty| {
623 PlaceholderReplacer::replace_placeholders(
632 .unwrap_or_else(|| ty.super_fold_with(self));
638 obligations.len = ?self.obligations.len(),
639 "AssocTypeNormalizer: normalized type"
644 _ => ty.super_fold_with(self),
648 #[instrument(skip(self), level = "debug")]
649 fn fold_const(&mut self, constant: ty::Const<'tcx>) -> ty::Const<'tcx> {
650 let tcx = self.selcx.tcx();
651 if tcx.lazy_normalization() || !needs_normalization(&constant, self.param_env.reveal()) {
654 let constant = constant.super_fold_with(self);
655 debug!(?constant, ?self.param_env);
656 with_replaced_escaping_bound_vars(
660 |constant| constant.eval(tcx, self.param_env),
666 fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
667 if p.allow_normalization() && needs_normalization(&p, self.param_env.reveal()) {
668 p.super_fold_with(self)
675 pub struct BoundVarReplacer<'me, 'tcx> {
676 infcx: &'me InferCtxt<'tcx>,
677 // These three maps track the bound variable that were replaced by placeholders. It might be
678 // nice to remove these since we already have the `kind` in the placeholder; we really just need
679 // the `var` (but we *could* bring that into scope if we were to track them as we pass them).
680 mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
681 mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy>,
682 mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
683 // The current depth relative to *this* folding, *not* the entire normalization. In other words,
684 // the depth of binders we've passed here.
685 current_index: ty::DebruijnIndex,
686 // The `UniverseIndex` of the binding levels above us. These are optional, since we are lazy:
687 // we don't actually create a universe until we see a bound var we have to replace.
688 universe_indices: &'me mut Vec<Option<ty::UniverseIndex>>,
691 /// Executes `f` on `value` after replacing all escaping bound variables with placeholders
692 /// and then replaces these placeholders with the original bound variables in the result.
694 /// In most places, bound variables should be replaced right when entering a binder, making
695 /// this function unnecessary. However, normalization currently does not do that, so we have
696 /// to do this lazily.
698 /// You should not add any additional uses of this function, at least not without first
699 /// discussing it with t-types.
701 /// FIXME(@lcnr): We may even consider experimenting with eagerly replacing bound vars during
702 /// normalization as well, at which point this function will be unnecessary and can be removed.
703 pub fn with_replaced_escaping_bound_vars<'a, 'tcx, T: TypeFoldable<'tcx>, R: TypeFoldable<'tcx>>(
704 infcx: &'a InferCtxt<'tcx>,
705 universe_indices: &'a mut Vec<Option<ty::UniverseIndex>>,
707 f: impl FnOnce(T) -> R,
709 if value.has_escaping_bound_vars() {
710 let (value, mapped_regions, mapped_types, mapped_consts) =
711 BoundVarReplacer::replace_bound_vars(infcx, universe_indices, value);
712 let result = f(value);
713 PlaceholderReplacer::replace_placeholders(
726 impl<'me, 'tcx> BoundVarReplacer<'me, 'tcx> {
727 /// Returns `Some` if we *were* able to replace bound vars. If there are any bound vars that
728 /// use a binding level above `universe_indices.len()`, we fail.
729 pub fn replace_bound_vars<T: TypeFoldable<'tcx>>(
730 infcx: &'me InferCtxt<'tcx>,
731 universe_indices: &'me mut Vec<Option<ty::UniverseIndex>>,
735 BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
736 BTreeMap<ty::PlaceholderType, ty::BoundTy>,
737 BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
739 let mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion> = BTreeMap::new();
740 let mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy> = BTreeMap::new();
741 let mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar> = BTreeMap::new();
743 let mut replacer = BoundVarReplacer {
748 current_index: ty::INNERMOST,
752 let value = value.fold_with(&mut replacer);
754 (value, replacer.mapped_regions, replacer.mapped_types, replacer.mapped_consts)
757 fn universe_for(&mut self, debruijn: ty::DebruijnIndex) -> ty::UniverseIndex {
758 let infcx = self.infcx;
760 self.universe_indices.len() + self.current_index.as_usize() - debruijn.as_usize() - 1;
761 let universe = self.universe_indices[index].unwrap_or_else(|| {
762 for i in self.universe_indices.iter_mut().take(index + 1) {
763 *i = i.or_else(|| Some(infcx.create_next_universe()))
765 self.universe_indices[index].unwrap()
771 impl<'tcx> TypeFolder<'tcx> for BoundVarReplacer<'_, 'tcx> {
772 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
776 fn fold_binder<T: TypeFoldable<'tcx>>(
778 t: ty::Binder<'tcx, T>,
779 ) -> ty::Binder<'tcx, T> {
780 self.current_index.shift_in(1);
781 let t = t.super_fold_with(self);
782 self.current_index.shift_out(1);
786 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
788 ty::ReLateBound(debruijn, _)
789 if debruijn.as_usize() + 1
790 > self.current_index.as_usize() + self.universe_indices.len() =>
792 bug!("Bound vars outside of `self.universe_indices`");
794 ty::ReLateBound(debruijn, br) if debruijn >= self.current_index => {
795 let universe = self.universe_for(debruijn);
796 let p = ty::PlaceholderRegion { universe, name: br.kind };
797 self.mapped_regions.insert(p, br);
798 self.infcx.tcx.mk_region(ty::RePlaceholder(p))
804 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
806 ty::Bound(debruijn, _)
807 if debruijn.as_usize() + 1
808 > self.current_index.as_usize() + self.universe_indices.len() =>
810 bug!("Bound vars outside of `self.universe_indices`");
812 ty::Bound(debruijn, bound_ty) if debruijn >= self.current_index => {
813 let universe = self.universe_for(debruijn);
814 let p = ty::PlaceholderType { universe, name: bound_ty.var };
815 self.mapped_types.insert(p, bound_ty);
816 self.infcx.tcx.mk_ty(ty::Placeholder(p))
818 _ if t.has_vars_bound_at_or_above(self.current_index) => t.super_fold_with(self),
823 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
825 ty::ConstKind::Bound(debruijn, _)
826 if debruijn.as_usize() + 1
827 > self.current_index.as_usize() + self.universe_indices.len() =>
829 bug!("Bound vars outside of `self.universe_indices`");
831 ty::ConstKind::Bound(debruijn, bound_const) if debruijn >= self.current_index => {
832 let universe = self.universe_for(debruijn);
833 let p = ty::PlaceholderConst { universe, name: bound_const };
834 self.mapped_consts.insert(p, bound_const);
835 self.infcx.tcx.mk_const(p, ct.ty())
837 _ => ct.super_fold_with(self),
841 fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
842 if p.has_vars_bound_at_or_above(self.current_index) { p.super_fold_with(self) } else { p }
846 /// The inverse of [`BoundVarReplacer`]: replaces placeholders with the bound vars from which they came.
847 pub struct PlaceholderReplacer<'me, 'tcx> {
848 infcx: &'me InferCtxt<'tcx>,
849 mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
850 mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy>,
851 mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
852 universe_indices: &'me [Option<ty::UniverseIndex>],
853 current_index: ty::DebruijnIndex,
856 impl<'me, 'tcx> PlaceholderReplacer<'me, 'tcx> {
857 pub fn replace_placeholders<T: TypeFoldable<'tcx>>(
858 infcx: &'me InferCtxt<'tcx>,
859 mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
860 mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy>,
861 mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
862 universe_indices: &'me [Option<ty::UniverseIndex>],
865 let mut replacer = PlaceholderReplacer {
871 current_index: ty::INNERMOST,
873 value.fold_with(&mut replacer)
877 impl<'tcx> TypeFolder<'tcx> for PlaceholderReplacer<'_, 'tcx> {
878 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
882 fn fold_binder<T: TypeFoldable<'tcx>>(
884 t: ty::Binder<'tcx, T>,
885 ) -> ty::Binder<'tcx, T> {
886 if !t.has_placeholders() && !t.has_infer_regions() {
889 self.current_index.shift_in(1);
890 let t = t.super_fold_with(self);
891 self.current_index.shift_out(1);
895 fn fold_region(&mut self, r0: ty::Region<'tcx>) -> ty::Region<'tcx> {
901 .unwrap_region_constraints()
902 .opportunistic_resolve_region(self.infcx.tcx, r0),
907 ty::RePlaceholder(p) => {
908 let replace_var = self.mapped_regions.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_region(ty::ReLateBound(db, *replace_var))
927 debug!(?r0, ?r1, ?r2, "fold_region");
932 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
934 ty::Placeholder(p) => {
935 let replace_var = self.mapped_types.get(&p);
937 Some(replace_var) => {
941 .position(|u| matches!(u, Some(pu) if *pu == p.universe))
942 .unwrap_or_else(|| bug!("Unexpected placeholder universe."));
943 let db = ty::DebruijnIndex::from_usize(
944 self.universe_indices.len() - index + self.current_index.as_usize() - 1,
946 self.tcx().mk_ty(ty::Bound(db, *replace_var))
952 _ if ty.has_placeholders() || ty.has_infer_regions() => ty.super_fold_with(self),
957 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
958 if let ty::ConstKind::Placeholder(p) = ct.kind() {
959 let replace_var = self.mapped_consts.get(&p);
961 Some(replace_var) => {
965 .position(|u| matches!(u, Some(pu) if *pu == p.universe))
966 .unwrap_or_else(|| bug!("Unexpected placeholder universe."));
967 let db = ty::DebruijnIndex::from_usize(
968 self.universe_indices.len() - index + self.current_index.as_usize() - 1,
970 self.tcx().mk_const(ty::ConstKind::Bound(db, *replace_var), ct.ty())
975 ct.super_fold_with(self)
980 /// The guts of `normalize`: normalize a specific projection like `<T
981 /// as Trait>::Item`. The result is always a type (and possibly
982 /// additional obligations). If ambiguity arises, which implies that
983 /// there are unresolved type variables in the projection, we will
984 /// substitute a fresh type variable `$X` and generate a new
985 /// obligation `<T as Trait>::Item == $X` for later.
986 pub fn normalize_projection_type<'a, 'b, 'tcx>(
987 selcx: &'a mut SelectionContext<'b, 'tcx>,
988 param_env: ty::ParamEnv<'tcx>,
989 projection_ty: ty::ProjectionTy<'tcx>,
990 cause: ObligationCause<'tcx>,
992 obligations: &mut Vec<PredicateObligation<'tcx>>,
994 opt_normalize_projection_type(
1004 .unwrap_or_else(move || {
1005 // if we bottom out in ambiguity, create a type variable
1006 // and a deferred predicate to resolve this when more type
1007 // information is available.
1009 selcx.infcx.infer_projection(param_env, projection_ty, cause, depth + 1, obligations).into()
1013 /// The guts of `normalize`: normalize a specific projection like `<T
1014 /// as Trait>::Item`. The result is always a type (and possibly
1015 /// additional obligations). Returns `None` in the case of ambiguity,
1016 /// which indicates that there are unbound type variables.
1018 /// This function used to return `Option<NormalizedTy<'tcx>>`, which contains a
1019 /// `Ty<'tcx>` and an obligations vector. But that obligation vector was very
1020 /// often immediately appended to another obligations vector. So now this
1021 /// function takes an obligations vector and appends to it directly, which is
1022 /// slightly uglier but avoids the need for an extra short-lived allocation.
1023 #[instrument(level = "debug", skip(selcx, param_env, cause, obligations))]
1024 fn opt_normalize_projection_type<'a, 'b, 'tcx>(
1025 selcx: &'a mut SelectionContext<'b, 'tcx>,
1026 param_env: ty::ParamEnv<'tcx>,
1027 projection_ty: ty::ProjectionTy<'tcx>,
1028 cause: ObligationCause<'tcx>,
1030 obligations: &mut Vec<PredicateObligation<'tcx>>,
1031 ) -> Result<Option<Term<'tcx>>, InProgress> {
1032 let infcx = selcx.infcx;
1033 // Don't use the projection cache in intercrate mode -
1034 // the `infcx` may be re-used between intercrate in non-intercrate
1035 // mode, which could lead to using incorrect cache results.
1036 let use_cache = !selcx.is_intercrate();
1038 let projection_ty = infcx.resolve_vars_if_possible(projection_ty);
1039 let cache_key = ProjectionCacheKey::new(projection_ty);
1041 // FIXME(#20304) For now, I am caching here, which is good, but it
1042 // means we don't capture the type variables that are created in
1043 // the case of ambiguity. Which means we may create a large stream
1044 // of such variables. OTOH, if we move the caching up a level, we
1045 // would not benefit from caching when proving `T: Trait<U=Foo>`
1046 // bounds. It might be the case that we want two distinct caches,
1047 // or else another kind of cache entry.
1049 let cache_result = if use_cache {
1050 infcx.inner.borrow_mut().projection_cache().try_start(cache_key)
1054 match cache_result {
1055 Ok(()) => debug!("no cache"),
1056 Err(ProjectionCacheEntry::Ambiguous) => {
1057 // If we found ambiguity the last time, that means we will continue
1058 // to do so until some type in the key changes (and we know it
1059 // hasn't, because we just fully resolved it).
1060 debug!("found cache entry: ambiguous");
1063 Err(ProjectionCacheEntry::InProgress) => {
1064 // Under lazy normalization, this can arise when
1065 // bootstrapping. That is, imagine an environment with a
1066 // where-clause like `A::B == u32`. Now, if we are asked
1067 // to normalize `A::B`, we will want to check the
1068 // where-clauses in scope. So we will try to unify `A::B`
1069 // with `A::B`, which can trigger a recursive
1072 debug!("found cache entry: in-progress");
1074 // Cache that normalizing this projection resulted in a cycle. This
1075 // should ensure that, unless this happens within a snapshot that's
1076 // rolled back, fulfillment or evaluation will notice the cycle.
1079 infcx.inner.borrow_mut().projection_cache().recur(cache_key);
1081 return Err(InProgress);
1083 Err(ProjectionCacheEntry::Recur) => {
1084 debug!("recur cache");
1085 return Err(InProgress);
1087 Err(ProjectionCacheEntry::NormalizedTy { ty, complete: _ }) => {
1088 // This is the hottest path in this function.
1090 // If we find the value in the cache, then return it along
1091 // with the obligations that went along with it. Note
1092 // that, when using a fulfillment context, these
1093 // obligations could in principle be ignored: they have
1094 // already been registered when the cache entry was
1095 // created (and hence the new ones will quickly be
1096 // discarded as duplicated). But when doing trait
1097 // evaluation this is not the case, and dropping the trait
1098 // evaluations can causes ICEs (e.g., #43132).
1099 debug!(?ty, "found normalized ty");
1100 obligations.extend(ty.obligations);
1101 return Ok(Some(ty.value));
1103 Err(ProjectionCacheEntry::Error) => {
1104 debug!("opt_normalize_projection_type: found error");
1105 let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth);
1106 obligations.extend(result.obligations);
1107 return Ok(Some(result.value.into()));
1112 Obligation::with_depth(selcx.tcx(), cause.clone(), depth, param_env, projection_ty);
1114 match project(selcx, &obligation) {
1115 Ok(Projected::Progress(Progress {
1116 term: projected_term,
1117 obligations: mut projected_obligations,
1119 // if projection succeeded, then what we get out of this
1120 // is also non-normalized (consider: it was derived from
1121 // an impl, where-clause etc) and hence we must
1124 let projected_term = selcx.infcx.resolve_vars_if_possible(projected_term);
1126 let mut result = if projected_term.has_projections() {
1127 let mut normalizer = AssocTypeNormalizer::new(
1132 &mut projected_obligations,
1134 let normalized_ty = normalizer.fold(projected_term);
1136 Normalized { value: normalized_ty, obligations: projected_obligations }
1138 Normalized { value: projected_term, obligations: projected_obligations }
1141 let mut deduped: SsoHashSet<_> = Default::default();
1142 result.obligations.drain_filter(|projected_obligation| {
1143 if !deduped.insert(projected_obligation.clone()) {
1150 infcx.inner.borrow_mut().projection_cache().insert_term(cache_key, result.clone());
1152 obligations.extend(result.obligations);
1153 Ok(Some(result.value))
1155 Ok(Projected::NoProgress(projected_ty)) => {
1156 let result = Normalized { value: projected_ty, obligations: vec![] };
1158 infcx.inner.borrow_mut().projection_cache().insert_term(cache_key, result.clone());
1160 // No need to extend `obligations`.
1161 Ok(Some(result.value))
1163 Err(ProjectionError::TooManyCandidates) => {
1164 debug!("opt_normalize_projection_type: too many candidates");
1166 infcx.inner.borrow_mut().projection_cache().ambiguous(cache_key);
1170 Err(ProjectionError::TraitSelectionError(_)) => {
1171 debug!("opt_normalize_projection_type: ERROR");
1172 // if we got an error processing the `T as Trait` part,
1173 // just return `ty::err` but add the obligation `T :
1174 // Trait`, which when processed will cause the error to be
1178 infcx.inner.borrow_mut().projection_cache().error(cache_key);
1180 let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth);
1181 obligations.extend(result.obligations);
1182 Ok(Some(result.value.into()))
1187 /// If we are projecting `<T as Trait>::Item`, but `T: Trait` does not
1188 /// hold. In various error cases, we cannot generate a valid
1189 /// normalized projection. Therefore, we create an inference variable
1190 /// return an associated obligation that, when fulfilled, will lead to
1193 /// Note that we used to return `Error` here, but that was quite
1194 /// dubious -- the premise was that an error would *eventually* be
1195 /// reported, when the obligation was processed. But in general once
1196 /// you see an `Error` you are supposed to be able to assume that an
1197 /// error *has been* reported, so that you can take whatever heuristic
1198 /// paths you want to take. To make things worse, it was possible for
1199 /// cycles to arise, where you basically had a setup like `<MyType<$0>
1200 /// as Trait>::Foo == $0`. Here, normalizing `<MyType<$0> as
1201 /// Trait>::Foo> to `[type error]` would lead to an obligation of
1202 /// `<MyType<[type error]> as Trait>::Foo`. We are supposed to report
1203 /// an error for this obligation, but we legitimately should not,
1204 /// because it contains `[type error]`. Yuck! (See issue #29857 for
1205 /// one case where this arose.)
1206 fn normalize_to_error<'a, 'tcx>(
1207 selcx: &mut SelectionContext<'a, 'tcx>,
1208 param_env: ty::ParamEnv<'tcx>,
1209 projection_ty: ty::ProjectionTy<'tcx>,
1210 cause: ObligationCause<'tcx>,
1212 ) -> NormalizedTy<'tcx> {
1213 let trait_ref = ty::Binder::dummy(projection_ty.trait_ref(selcx.tcx()));
1214 let trait_obligation = Obligation {
1216 recursion_depth: depth,
1218 predicate: trait_ref.without_const().to_predicate(selcx.tcx()),
1220 let tcx = selcx.infcx.tcx;
1221 let def_id = projection_ty.item_def_id;
1222 let new_value = selcx.infcx.next_ty_var(TypeVariableOrigin {
1223 kind: TypeVariableOriginKind::NormalizeProjectionType,
1224 span: tcx.def_span(def_id),
1226 Normalized { value: new_value, obligations: vec![trait_obligation] }
1229 enum Projected<'tcx> {
1230 Progress(Progress<'tcx>),
1231 NoProgress(ty::Term<'tcx>),
1234 struct Progress<'tcx> {
1235 term: ty::Term<'tcx>,
1236 obligations: Vec<PredicateObligation<'tcx>>,
1239 impl<'tcx> Progress<'tcx> {
1240 fn error(tcx: TyCtxt<'tcx>) -> Self {
1241 Progress { term: tcx.ty_error().into(), obligations: vec![] }
1244 fn with_addl_obligations(mut self, mut obligations: Vec<PredicateObligation<'tcx>>) -> Self {
1245 self.obligations.append(&mut obligations);
1250 /// Computes the result of a projection type (if we can).
1253 /// - `obligation` must be fully normalized
1254 #[instrument(level = "info", skip(selcx))]
1255 fn project<'cx, 'tcx>(
1256 selcx: &mut SelectionContext<'cx, 'tcx>,
1257 obligation: &ProjectionTyObligation<'tcx>,
1258 ) -> Result<Projected<'tcx>, ProjectionError<'tcx>> {
1259 if !selcx.tcx().recursion_limit().value_within_limit(obligation.recursion_depth) {
1260 // This should really be an immediate error, but some existing code
1261 // relies on being able to recover from this.
1262 return Err(ProjectionError::TraitSelectionError(SelectionError::Overflow(
1263 OverflowError::Canonical,
1267 if obligation.predicate.references_error() {
1268 return Ok(Projected::Progress(Progress::error(selcx.tcx())));
1271 let mut candidates = ProjectionCandidateSet::None;
1273 assemble_candidate_for_impl_trait_in_trait(selcx, obligation, &mut candidates);
1275 // Make sure that the following procedures are kept in order. ParamEnv
1276 // needs to be first because it has highest priority, and Select checks
1277 // the return value of push_candidate which assumes it's ran at last.
1278 assemble_candidates_from_param_env(selcx, obligation, &mut candidates);
1280 assemble_candidates_from_trait_def(selcx, obligation, &mut candidates);
1282 assemble_candidates_from_object_ty(selcx, obligation, &mut candidates);
1284 if let ProjectionCandidateSet::Single(ProjectionCandidate::Object(_)) = candidates {
1285 // Avoid normalization cycle from selection (see
1286 // `assemble_candidates_from_object_ty`).
1287 // FIXME(lazy_normalization): Lazy normalization should save us from
1288 // having to special case this.
1290 assemble_candidates_from_impls(selcx, obligation, &mut candidates);
1294 ProjectionCandidateSet::Single(candidate) => {
1295 Ok(Projected::Progress(confirm_candidate(selcx, obligation, candidate)))
1297 ProjectionCandidateSet::None => Ok(Projected::NoProgress(
1298 // FIXME(associated_const_generics): this may need to change in the future?
1299 // need to investigate whether or not this is fine.
1302 .mk_projection(obligation.predicate.item_def_id, obligation.predicate.substs)
1305 // Error occurred while trying to processing impls.
1306 ProjectionCandidateSet::Error(e) => Err(ProjectionError::TraitSelectionError(e)),
1307 // Inherent ambiguity that prevents us from even enumerating the
1309 ProjectionCandidateSet::Ambiguous => Err(ProjectionError::TooManyCandidates),
1313 /// If the predicate's item is an `ImplTraitPlaceholder`, we do a select on the
1314 /// corresponding trait ref. If this yields an `impl`, then we're able to project
1315 /// to a concrete type, since we have an `impl`'s method to provide the RPITIT.
1316 fn assemble_candidate_for_impl_trait_in_trait<'cx, 'tcx>(
1317 selcx: &mut SelectionContext<'cx, 'tcx>,
1318 obligation: &ProjectionTyObligation<'tcx>,
1319 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1321 let tcx = selcx.tcx();
1322 if tcx.def_kind(obligation.predicate.item_def_id) == DefKind::ImplTraitPlaceholder {
1323 let trait_fn_def_id = tcx.impl_trait_in_trait_parent(obligation.predicate.item_def_id);
1324 // If we are trying to project an RPITIT with trait's default `Self` parameter,
1325 // then we must be within a default trait body.
1326 if obligation.predicate.self_ty()
1327 == ty::InternalSubsts::identity_for_item(tcx, obligation.predicate.item_def_id)
1329 && tcx.associated_item(trait_fn_def_id).defaultness(tcx).has_value()
1331 candidate_set.push_candidate(ProjectionCandidate::ImplTraitInTrait(
1332 ImplTraitInTraitCandidate::Trait,
1337 let trait_def_id = tcx.parent(trait_fn_def_id);
1339 obligation.predicate.substs.truncate_to(tcx, tcx.generics_of(trait_def_id));
1340 // FIXME(named-returns): Binders
1341 let trait_predicate =
1342 ty::Binder::dummy(ty::TraitRef { def_id: trait_def_id, substs: trait_substs });
1344 let _ = selcx.infcx.commit_if_ok(|_| {
1345 match selcx.select(&obligation.with(tcx, trait_predicate)) {
1346 Ok(Some(super::ImplSource::UserDefined(data))) => {
1347 candidate_set.push_candidate(ProjectionCandidate::ImplTraitInTrait(
1348 ImplTraitInTraitCandidate::Impl(data),
1353 candidate_set.mark_ambiguous();
1357 // Don't know enough about the impl to provide a useful signature
1361 debug!(error = ?e, "selection error");
1362 candidate_set.mark_error(e);
1370 /// The first thing we have to do is scan through the parameter
1371 /// environment to see whether there are any projection predicates
1372 /// there that can answer this question.
1373 fn assemble_candidates_from_param_env<'cx, 'tcx>(
1374 selcx: &mut SelectionContext<'cx, 'tcx>,
1375 obligation: &ProjectionTyObligation<'tcx>,
1376 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1378 assemble_candidates_from_predicates(
1382 ProjectionCandidate::ParamEnv,
1383 obligation.param_env.caller_bounds().iter(),
1388 /// In the case of a nested projection like `<<A as Foo>::FooT as Bar>::BarT`, we may find
1389 /// that the definition of `Foo` has some clues:
1391 /// ```ignore (illustrative)
1393 /// type FooT : Bar<BarT=i32>
1397 /// Here, for example, we could conclude that the result is `i32`.
1398 fn assemble_candidates_from_trait_def<'cx, 'tcx>(
1399 selcx: &mut SelectionContext<'cx, 'tcx>,
1400 obligation: &ProjectionTyObligation<'tcx>,
1401 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1403 debug!("assemble_candidates_from_trait_def(..)");
1405 let tcx = selcx.tcx();
1406 // Check whether the self-type is itself a projection.
1407 // If so, extract what we know from the trait and try to come up with a good answer.
1408 let bounds = match *obligation.predicate.self_ty().kind() {
1409 ty::Projection(ref data) => tcx.bound_item_bounds(data.item_def_id).subst(tcx, data.substs),
1410 ty::Opaque(def_id, substs) => tcx.bound_item_bounds(def_id).subst(tcx, substs),
1411 ty::Infer(ty::TyVar(_)) => {
1412 // If the self-type is an inference variable, then it MAY wind up
1413 // being a projected type, so induce an ambiguity.
1414 candidate_set.mark_ambiguous();
1420 assemble_candidates_from_predicates(
1424 ProjectionCandidate::TraitDef,
1430 /// In the case of a trait object like
1431 /// `<dyn Iterator<Item = ()> as Iterator>::Item` we can use the existential
1432 /// predicate in the trait object.
1434 /// We don't go through the select candidate for these bounds to avoid cycles:
1435 /// In the above case, `dyn Iterator<Item = ()>: Iterator` would create a
1436 /// nested obligation of `<dyn Iterator<Item = ()> as Iterator>::Item: Sized`,
1437 /// this then has to be normalized without having to prove
1438 /// `dyn Iterator<Item = ()>: Iterator` again.
1439 fn assemble_candidates_from_object_ty<'cx, 'tcx>(
1440 selcx: &mut SelectionContext<'cx, 'tcx>,
1441 obligation: &ProjectionTyObligation<'tcx>,
1442 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1444 debug!("assemble_candidates_from_object_ty(..)");
1446 let tcx = selcx.tcx();
1448 let self_ty = obligation.predicate.self_ty();
1449 let object_ty = selcx.infcx.shallow_resolve(self_ty);
1450 let data = match object_ty.kind() {
1451 ty::Dynamic(data, ..) => data,
1452 ty::Infer(ty::TyVar(_)) => {
1453 // If the self-type is an inference variable, then it MAY wind up
1454 // being an object type, so induce an ambiguity.
1455 candidate_set.mark_ambiguous();
1460 let env_predicates = data
1461 .projection_bounds()
1462 .filter(|bound| bound.item_def_id() == obligation.predicate.item_def_id)
1463 .map(|p| p.with_self_ty(tcx, object_ty).to_predicate(tcx));
1465 assemble_candidates_from_predicates(
1469 ProjectionCandidate::Object,
1477 skip(selcx, candidate_set, ctor, env_predicates, potentially_unnormalized_candidates)
1479 fn assemble_candidates_from_predicates<'cx, 'tcx>(
1480 selcx: &mut SelectionContext<'cx, 'tcx>,
1481 obligation: &ProjectionTyObligation<'tcx>,
1482 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1483 ctor: fn(ty::PolyProjectionPredicate<'tcx>) -> ProjectionCandidate<'tcx>,
1484 env_predicates: impl Iterator<Item = ty::Predicate<'tcx>>,
1485 potentially_unnormalized_candidates: bool,
1487 let infcx = selcx.infcx;
1488 for predicate in env_predicates {
1489 let bound_predicate = predicate.kind();
1490 if let ty::PredicateKind::Clause(ty::Clause::Projection(data)) =
1491 predicate.kind().skip_binder()
1493 let data = bound_predicate.rebind(data);
1494 if data.projection_def_id() != obligation.predicate.item_def_id {
1498 let is_match = infcx.probe(|_| {
1499 selcx.match_projection_projections(
1502 potentially_unnormalized_candidates,
1507 ProjectionMatchesProjection::Yes => {
1508 candidate_set.push_candidate(ctor(data));
1510 if potentially_unnormalized_candidates
1511 && !obligation.predicate.has_non_region_infer()
1513 // HACK: Pick the first trait def candidate for a fully
1514 // inferred predicate. This is to allow duplicates that
1515 // differ only in normalization.
1519 ProjectionMatchesProjection::Ambiguous => {
1520 candidate_set.mark_ambiguous();
1522 ProjectionMatchesProjection::No => {}
1528 #[instrument(level = "debug", skip(selcx, obligation, candidate_set))]
1529 fn assemble_candidates_from_impls<'cx, 'tcx>(
1530 selcx: &mut SelectionContext<'cx, 'tcx>,
1531 obligation: &ProjectionTyObligation<'tcx>,
1532 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1534 // Can't assemble candidate from impl for RPITIT
1535 if selcx.tcx().def_kind(obligation.predicate.item_def_id) == DefKind::ImplTraitPlaceholder {
1539 // If we are resolving `<T as TraitRef<...>>::Item == Type`,
1540 // start out by selecting the predicate `T as TraitRef<...>`:
1541 let poly_trait_ref = ty::Binder::dummy(obligation.predicate.trait_ref(selcx.tcx()));
1542 let trait_obligation = obligation.with(selcx.tcx(), poly_trait_ref);
1543 let _ = selcx.infcx.commit_if_ok(|_| {
1544 let impl_source = match selcx.select(&trait_obligation) {
1545 Ok(Some(impl_source)) => impl_source,
1547 candidate_set.mark_ambiguous();
1551 debug!(error = ?e, "selection error");
1552 candidate_set.mark_error(e);
1557 let eligible = match &impl_source {
1558 super::ImplSource::Closure(_)
1559 | super::ImplSource::Generator(_)
1560 | super::ImplSource::Future(_)
1561 | super::ImplSource::FnPointer(_)
1562 | super::ImplSource::TraitAlias(_) => true,
1563 super::ImplSource::UserDefined(impl_data) => {
1564 // We have to be careful when projecting out of an
1565 // impl because of specialization. If we are not in
1566 // codegen (i.e., projection mode is not "any"), and the
1567 // impl's type is declared as default, then we disable
1568 // projection (even if the trait ref is fully
1569 // monomorphic). In the case where trait ref is not
1570 // fully monomorphic (i.e., includes type parameters),
1571 // this is because those type parameters may
1572 // ultimately be bound to types from other crates that
1573 // may have specialized impls we can't see. In the
1574 // case where the trait ref IS fully monomorphic, this
1575 // is a policy decision that we made in the RFC in
1576 // order to preserve flexibility for the crate that
1577 // defined the specializable impl to specialize later
1578 // for existing types.
1580 // In either case, we handle this by not adding a
1581 // candidate for an impl if it contains a `default`
1584 // NOTE: This should be kept in sync with the similar code in
1585 // `rustc_ty_utils::instance::resolve_associated_item()`.
1587 assoc_def(selcx, impl_data.impl_def_id, obligation.predicate.item_def_id)
1588 .map_err(|ErrorGuaranteed { .. }| ())?;
1590 if node_item.is_final() {
1591 // Non-specializable items are always projectable.
1594 // Only reveal a specializable default if we're past type-checking
1595 // and the obligation is monomorphic, otherwise passes such as
1596 // transmute checking and polymorphic MIR optimizations could
1597 // get a result which isn't correct for all monomorphizations.
1598 if obligation.param_env.reveal() == Reveal::All {
1599 // NOTE(eddyb) inference variables can resolve to parameters, so
1600 // assume `poly_trait_ref` isn't monomorphic, if it contains any.
1601 let poly_trait_ref = selcx.infcx.resolve_vars_if_possible(poly_trait_ref);
1602 !poly_trait_ref.still_further_specializable()
1605 assoc_ty = ?selcx.tcx().def_path_str(node_item.item.def_id),
1606 ?obligation.predicate,
1607 "assemble_candidates_from_impls: not eligible due to default",
1613 super::ImplSource::Builtin(..) => {
1614 // While a builtin impl may be known to exist, the associated type may not yet
1615 // be known. Any type with multiple potential associated types is therefore
1617 let self_ty = selcx.infcx.shallow_resolve(obligation.predicate.self_ty());
1619 let lang_items = selcx.tcx().lang_items();
1620 if lang_items.discriminant_kind_trait() == Some(poly_trait_ref.def_id()) {
1621 match self_ty.kind() {
1639 | ty::GeneratorWitness(..)
1642 // Integers and floats always have `u8` as their discriminant.
1643 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(..)) => true,
1645 // type parameters, opaques, and unnormalized projections have pointer
1646 // metadata if they're known (e.g. by the param_env) to be sized
1648 | ty::Projection(..)
1651 | ty::Placeholder(..)
1653 | ty::Error(_) => false,
1655 } else if lang_items.pointee_trait() == Some(poly_trait_ref.def_id()) {
1656 let tail = selcx.tcx().struct_tail_with_normalize(
1659 // We throw away any obligations we get from this, since we normalize
1660 // and confirm these obligations once again during confirmation
1661 normalize_with_depth(
1663 obligation.param_env,
1664 obligation.cause.clone(),
1665 obligation.recursion_depth + 1,
1689 | ty::GeneratorWitness(..)
1691 // Extern types have unit metadata, according to RFC 2850
1693 // If returned by `struct_tail_without_normalization` this is a unit struct
1694 // without any fields, or not a struct, and therefore is Sized.
1696 // If returned by `struct_tail_without_normalization` this is the empty tuple.
1698 // Integers and floats are always Sized, and so have unit type metadata.
1699 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(..)) => true,
1701 // type parameters, opaques, and unnormalized projections have pointer
1702 // metadata if they're known (e.g. by the param_env) to be sized
1703 ty::Param(_) | ty::Projection(..) | ty::Opaque(..)
1704 if selcx.infcx.predicate_must_hold_modulo_regions(
1708 selcx.tcx().at(obligation.cause.span()).mk_trait_ref(LangItem::Sized, [self_ty]),
1717 // FIXME(compiler-errors): are Bound and Placeholder types ever known sized?
1719 | ty::Projection(..)
1722 | ty::Placeholder(..)
1725 if tail.has_infer_types() {
1726 candidate_set.mark_ambiguous();
1732 bug!("unexpected builtin trait with associated type: {poly_trait_ref:?}")
1735 super::ImplSource::Param(..) => {
1736 // This case tell us nothing about the value of an
1737 // associated type. Consider:
1740 // trait SomeTrait { type Foo; }
1741 // fn foo<T:SomeTrait>(...) { }
1744 // If the user writes `<T as SomeTrait>::Foo`, then the `T
1745 // : SomeTrait` binding does not help us decide what the
1746 // type `Foo` is (at least, not more specifically than
1747 // what we already knew).
1749 // But wait, you say! What about an example like this:
1752 // fn bar<T:SomeTrait<Foo=usize>>(...) { ... }
1755 // Doesn't the `T : SomeTrait<Foo=usize>` predicate help
1756 // resolve `T::Foo`? And of course it does, but in fact
1757 // that single predicate is desugared into two predicates
1758 // in the compiler: a trait predicate (`T : SomeTrait`) and a
1759 // projection. And the projection where clause is handled
1760 // in `assemble_candidates_from_param_env`.
1763 super::ImplSource::Object(_) => {
1764 // Handled by the `Object` projection candidate. See
1765 // `assemble_candidates_from_object_ty` for an explanation of
1766 // why we special case object types.
1769 super::ImplSource::AutoImpl(..)
1770 | super::ImplSource::TraitUpcasting(_)
1771 | super::ImplSource::ConstDestruct(_) => {
1772 // These traits have no associated types.
1773 selcx.tcx().sess.delay_span_bug(
1774 obligation.cause.span,
1775 &format!("Cannot project an associated type from `{:?}`", impl_source),
1782 if candidate_set.push_candidate(ProjectionCandidate::Select(impl_source)) {
1793 fn confirm_candidate<'cx, 'tcx>(
1794 selcx: &mut SelectionContext<'cx, 'tcx>,
1795 obligation: &ProjectionTyObligation<'tcx>,
1796 candidate: ProjectionCandidate<'tcx>,
1797 ) -> Progress<'tcx> {
1798 debug!(?obligation, ?candidate, "confirm_candidate");
1799 let mut progress = match candidate {
1800 ProjectionCandidate::ParamEnv(poly_projection)
1801 | ProjectionCandidate::Object(poly_projection) => {
1802 confirm_param_env_candidate(selcx, obligation, poly_projection, false)
1805 ProjectionCandidate::TraitDef(poly_projection) => {
1806 confirm_param_env_candidate(selcx, obligation, poly_projection, true)
1809 ProjectionCandidate::Select(impl_source) => {
1810 confirm_select_candidate(selcx, obligation, impl_source)
1812 ProjectionCandidate::ImplTraitInTrait(ImplTraitInTraitCandidate::Impl(data)) => {
1813 confirm_impl_trait_in_trait_candidate(selcx, obligation, data)
1815 // If we're projecting an RPITIT for a default trait body, that's just
1816 // the same def-id, but as an opaque type (with regular RPIT semantics).
1817 ProjectionCandidate::ImplTraitInTrait(ImplTraitInTraitCandidate::Trait) => Progress {
1820 .mk_opaque(obligation.predicate.item_def_id, obligation.predicate.substs)
1822 obligations: vec![],
1826 // When checking for cycle during evaluation, we compare predicates with
1827 // "syntactic" equality. Since normalization generally introduces a type
1828 // with new region variables, we need to resolve them to existing variables
1829 // when possible for this to work. See `auto-trait-projection-recursion.rs`
1830 // for a case where this matters.
1831 if progress.term.has_infer_regions() {
1832 progress.term = progress.term.fold_with(&mut OpportunisticRegionResolver::new(selcx.infcx));
1837 fn confirm_select_candidate<'cx, 'tcx>(
1838 selcx: &mut SelectionContext<'cx, 'tcx>,
1839 obligation: &ProjectionTyObligation<'tcx>,
1840 impl_source: Selection<'tcx>,
1841 ) -> Progress<'tcx> {
1843 super::ImplSource::UserDefined(data) => confirm_impl_candidate(selcx, obligation, data),
1844 super::ImplSource::Generator(data) => confirm_generator_candidate(selcx, obligation, data),
1845 super::ImplSource::Future(data) => confirm_future_candidate(selcx, obligation, data),
1846 super::ImplSource::Closure(data) => confirm_closure_candidate(selcx, obligation, data),
1847 super::ImplSource::FnPointer(data) => confirm_fn_pointer_candidate(selcx, obligation, data),
1848 super::ImplSource::Builtin(data) => confirm_builtin_candidate(selcx, obligation, data),
1849 super::ImplSource::Object(_)
1850 | super::ImplSource::AutoImpl(..)
1851 | super::ImplSource::Param(..)
1852 | super::ImplSource::TraitUpcasting(_)
1853 | super::ImplSource::TraitAlias(..)
1854 | super::ImplSource::ConstDestruct(_) => {
1855 // we don't create Select candidates with this kind of resolution
1857 obligation.cause.span,
1858 "Cannot project an associated type from `{:?}`",
1865 fn confirm_generator_candidate<'cx, 'tcx>(
1866 selcx: &mut SelectionContext<'cx, 'tcx>,
1867 obligation: &ProjectionTyObligation<'tcx>,
1868 impl_source: ImplSourceGeneratorData<'tcx, PredicateObligation<'tcx>>,
1869 ) -> Progress<'tcx> {
1870 let gen_sig = impl_source.substs.as_generator().poly_sig();
1871 let Normalized { value: gen_sig, obligations } = normalize_with_depth(
1873 obligation.param_env,
1874 obligation.cause.clone(),
1875 obligation.recursion_depth + 1,
1879 debug!(?obligation, ?gen_sig, ?obligations, "confirm_generator_candidate");
1881 let tcx = selcx.tcx();
1883 let gen_def_id = tcx.require_lang_item(LangItem::Generator, None);
1885 let predicate = super::util::generator_trait_ref_and_outputs(
1888 obligation.predicate.self_ty(),
1891 .map_bound(|(trait_ref, yield_ty, return_ty)| {
1892 let name = tcx.associated_item(obligation.predicate.item_def_id).name;
1893 let ty = if name == sym::Return {
1895 } else if name == sym::Yield {
1901 ty::ProjectionPredicate {
1902 projection_ty: ty::ProjectionTy {
1903 substs: trait_ref.substs,
1904 item_def_id: obligation.predicate.item_def_id,
1910 confirm_param_env_candidate(selcx, obligation, predicate, false)
1911 .with_addl_obligations(impl_source.nested)
1912 .with_addl_obligations(obligations)
1915 fn confirm_future_candidate<'cx, 'tcx>(
1916 selcx: &mut SelectionContext<'cx, 'tcx>,
1917 obligation: &ProjectionTyObligation<'tcx>,
1918 impl_source: ImplSourceFutureData<'tcx, PredicateObligation<'tcx>>,
1919 ) -> Progress<'tcx> {
1920 let gen_sig = impl_source.substs.as_generator().poly_sig();
1921 let Normalized { value: gen_sig, obligations } = normalize_with_depth(
1923 obligation.param_env,
1924 obligation.cause.clone(),
1925 obligation.recursion_depth + 1,
1929 debug!(?obligation, ?gen_sig, ?obligations, "confirm_future_candidate");
1931 let tcx = selcx.tcx();
1932 let fut_def_id = tcx.require_lang_item(LangItem::Future, None);
1934 let predicate = super::util::future_trait_ref_and_outputs(
1937 obligation.predicate.self_ty(),
1940 .map_bound(|(trait_ref, return_ty)| {
1941 debug_assert_eq!(tcx.associated_item(obligation.predicate.item_def_id).name, sym::Output);
1943 ty::ProjectionPredicate {
1944 projection_ty: ty::ProjectionTy {
1945 substs: trait_ref.substs,
1946 item_def_id: obligation.predicate.item_def_id,
1948 term: return_ty.into(),
1952 confirm_param_env_candidate(selcx, obligation, predicate, false)
1953 .with_addl_obligations(impl_source.nested)
1954 .with_addl_obligations(obligations)
1957 fn confirm_builtin_candidate<'cx, 'tcx>(
1958 selcx: &mut SelectionContext<'cx, 'tcx>,
1959 obligation: &ProjectionTyObligation<'tcx>,
1960 data: ImplSourceBuiltinData<PredicateObligation<'tcx>>,
1961 ) -> Progress<'tcx> {
1962 let tcx = selcx.tcx();
1963 let self_ty = obligation.predicate.self_ty();
1964 let substs = tcx.mk_substs([self_ty.into()].iter());
1965 let lang_items = tcx.lang_items();
1966 let item_def_id = obligation.predicate.item_def_id;
1967 let trait_def_id = tcx.trait_of_item(item_def_id).unwrap();
1968 let (term, obligations) = if lang_items.discriminant_kind_trait() == Some(trait_def_id) {
1969 let discriminant_def_id = tcx.require_lang_item(LangItem::Discriminant, None);
1970 assert_eq!(discriminant_def_id, item_def_id);
1972 (self_ty.discriminant_ty(tcx).into(), Vec::new())
1973 } else if lang_items.pointee_trait() == Some(trait_def_id) {
1974 let metadata_def_id = tcx.require_lang_item(LangItem::Metadata, None);
1975 assert_eq!(metadata_def_id, item_def_id);
1977 let mut obligations = Vec::new();
1978 let (metadata_ty, check_is_sized) = self_ty.ptr_metadata_ty(tcx, |ty| {
1979 normalize_with_depth_to(
1981 obligation.param_env,
1982 obligation.cause.clone(),
1983 obligation.recursion_depth + 1,
1989 let sized_predicate = ty::Binder::dummy(
1990 tcx.at(obligation.cause.span()).mk_trait_ref(LangItem::Sized, [self_ty]),
1993 obligations.push(obligation.with(tcx, sized_predicate));
1995 (metadata_ty.into(), obligations)
1997 bug!("unexpected builtin trait with associated type: {:?}", obligation.predicate);
2001 ty::ProjectionPredicate { projection_ty: ty::ProjectionTy { substs, item_def_id }, term };
2003 confirm_param_env_candidate(selcx, obligation, ty::Binder::dummy(predicate), false)
2004 .with_addl_obligations(obligations)
2005 .with_addl_obligations(data.nested)
2008 fn confirm_fn_pointer_candidate<'cx, 'tcx>(
2009 selcx: &mut SelectionContext<'cx, 'tcx>,
2010 obligation: &ProjectionTyObligation<'tcx>,
2011 fn_pointer_impl_source: ImplSourceFnPointerData<'tcx, PredicateObligation<'tcx>>,
2012 ) -> Progress<'tcx> {
2013 let fn_type = selcx.infcx.shallow_resolve(fn_pointer_impl_source.fn_ty);
2014 let sig = fn_type.fn_sig(selcx.tcx());
2015 let Normalized { value: sig, obligations } = normalize_with_depth(
2017 obligation.param_env,
2018 obligation.cause.clone(),
2019 obligation.recursion_depth + 1,
2023 confirm_callable_candidate(selcx, obligation, sig, util::TupleArgumentsFlag::Yes)
2024 .with_addl_obligations(fn_pointer_impl_source.nested)
2025 .with_addl_obligations(obligations)
2028 fn confirm_closure_candidate<'cx, 'tcx>(
2029 selcx: &mut SelectionContext<'cx, 'tcx>,
2030 obligation: &ProjectionTyObligation<'tcx>,
2031 impl_source: ImplSourceClosureData<'tcx, PredicateObligation<'tcx>>,
2032 ) -> Progress<'tcx> {
2033 let closure_sig = impl_source.substs.as_closure().sig();
2034 let Normalized { value: closure_sig, obligations } = normalize_with_depth(
2036 obligation.param_env,
2037 obligation.cause.clone(),
2038 obligation.recursion_depth + 1,
2042 debug!(?obligation, ?closure_sig, ?obligations, "confirm_closure_candidate");
2044 confirm_callable_candidate(selcx, obligation, closure_sig, util::TupleArgumentsFlag::No)
2045 .with_addl_obligations(impl_source.nested)
2046 .with_addl_obligations(obligations)
2049 fn confirm_callable_candidate<'cx, 'tcx>(
2050 selcx: &mut SelectionContext<'cx, 'tcx>,
2051 obligation: &ProjectionTyObligation<'tcx>,
2052 fn_sig: ty::PolyFnSig<'tcx>,
2053 flag: util::TupleArgumentsFlag,
2054 ) -> Progress<'tcx> {
2055 let tcx = selcx.tcx();
2057 debug!(?obligation, ?fn_sig, "confirm_callable_candidate");
2059 let fn_once_def_id = tcx.require_lang_item(LangItem::FnOnce, None);
2060 let fn_once_output_def_id = tcx.require_lang_item(LangItem::FnOnceOutput, None);
2062 let predicate = super::util::closure_trait_ref_and_return_type(
2065 obligation.predicate.self_ty(),
2069 .map_bound(|(trait_ref, ret_type)| ty::ProjectionPredicate {
2070 projection_ty: ty::ProjectionTy {
2071 substs: trait_ref.substs,
2072 item_def_id: fn_once_output_def_id,
2074 term: ret_type.into(),
2077 confirm_param_env_candidate(selcx, obligation, predicate, true)
2080 fn confirm_param_env_candidate<'cx, 'tcx>(
2081 selcx: &mut SelectionContext<'cx, 'tcx>,
2082 obligation: &ProjectionTyObligation<'tcx>,
2083 poly_cache_entry: ty::PolyProjectionPredicate<'tcx>,
2084 potentially_unnormalized_candidate: bool,
2085 ) -> Progress<'tcx> {
2086 let infcx = selcx.infcx;
2087 let cause = &obligation.cause;
2088 let param_env = obligation.param_env;
2090 let cache_entry = infcx.replace_bound_vars_with_fresh_vars(
2092 LateBoundRegionConversionTime::HigherRankedType,
2096 let cache_projection = cache_entry.projection_ty;
2097 let mut nested_obligations = Vec::new();
2098 let obligation_projection = obligation.predicate;
2099 let obligation_projection = ensure_sufficient_stack(|| {
2100 normalize_with_depth_to(
2102 obligation.param_env,
2103 obligation.cause.clone(),
2104 obligation.recursion_depth + 1,
2105 obligation_projection,
2106 &mut nested_obligations,
2109 let cache_projection = if potentially_unnormalized_candidate {
2110 ensure_sufficient_stack(|| {
2111 normalize_with_depth_to(
2113 obligation.param_env,
2114 obligation.cause.clone(),
2115 obligation.recursion_depth + 1,
2117 &mut nested_obligations,
2124 debug!(?cache_projection, ?obligation_projection);
2126 match infcx.at(cause, param_env).eq(cache_projection, obligation_projection) {
2127 Ok(InferOk { value: _, obligations }) => {
2128 nested_obligations.extend(obligations);
2129 assoc_ty_own_obligations(selcx, obligation, &mut nested_obligations);
2130 // FIXME(associated_const_equality): Handle consts here as well? Maybe this progress type should just take
2132 Progress { term: cache_entry.term, obligations: nested_obligations }
2136 "Failed to unify obligation `{:?}` with poly_projection `{:?}`: {:?}",
2137 obligation, poly_cache_entry, e,
2139 debug!("confirm_param_env_candidate: {}", msg);
2140 let err = infcx.tcx.ty_error_with_message(obligation.cause.span, &msg);
2141 Progress { term: err.into(), obligations: vec![] }
2146 fn confirm_impl_candidate<'cx, 'tcx>(
2147 selcx: &mut SelectionContext<'cx, 'tcx>,
2148 obligation: &ProjectionTyObligation<'tcx>,
2149 impl_impl_source: ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>>,
2150 ) -> Progress<'tcx> {
2151 let tcx = selcx.tcx();
2153 let ImplSourceUserDefinedData { impl_def_id, substs, mut nested } = impl_impl_source;
2154 let assoc_item_id = obligation.predicate.item_def_id;
2155 let trait_def_id = tcx.trait_id_of_impl(impl_def_id).unwrap();
2157 let param_env = obligation.param_env;
2158 let Ok(assoc_ty) = assoc_def(selcx, impl_def_id, assoc_item_id) else {
2159 return Progress { term: tcx.ty_error().into(), obligations: nested };
2162 if !assoc_ty.item.defaultness(tcx).has_value() {
2163 // This means that the impl is missing a definition for the
2164 // associated type. This error will be reported by the type
2165 // checker method `check_impl_items_against_trait`, so here we
2166 // just return Error.
2168 "confirm_impl_candidate: no associated type {:?} for {:?}",
2169 assoc_ty.item.name, obligation.predicate
2171 return Progress { term: tcx.ty_error().into(), obligations: nested };
2173 // If we're trying to normalize `<Vec<u32> as X>::A<S>` using
2174 //`impl<T> X for Vec<T> { type A<Y> = Box<Y>; }`, then:
2176 // * `obligation.predicate.substs` is `[Vec<u32>, S]`
2177 // * `substs` is `[u32]`
2178 // * `substs` ends up as `[u32, S]`
2179 let substs = obligation.predicate.substs.rebase_onto(tcx, trait_def_id, substs);
2181 translate_substs(selcx.infcx, param_env, impl_def_id, substs, assoc_ty.defining_node);
2182 let ty = tcx.bound_type_of(assoc_ty.item.def_id);
2183 let is_const = matches!(tcx.def_kind(assoc_ty.item.def_id), DefKind::AssocConst);
2184 let term: ty::EarlyBinder<ty::Term<'tcx>> = if is_const {
2185 let identity_substs =
2186 crate::traits::InternalSubsts::identity_for_item(tcx, assoc_ty.item.def_id);
2187 let did = ty::WithOptConstParam::unknown(assoc_ty.item.def_id);
2188 let kind = ty::ConstKind::Unevaluated(ty::UnevaluatedConst::new(did, identity_substs));
2189 ty.map_bound(|ty| tcx.mk_const(kind, ty).into())
2191 ty.map_bound(|ty| ty.into())
2193 if !check_substs_compatible(tcx, &assoc_ty.item, substs) {
2194 let err = tcx.ty_error_with_message(
2195 obligation.cause.span,
2196 "impl item and trait item have different parameters",
2198 Progress { term: err.into(), obligations: nested }
2200 assoc_ty_own_obligations(selcx, obligation, &mut nested);
2201 Progress { term: term.subst(tcx, substs), obligations: nested }
2205 // Verify that the trait item and its implementation have compatible substs lists
2206 fn check_substs_compatible<'tcx>(
2208 assoc_item: &ty::AssocItem,
2209 substs: ty::SubstsRef<'tcx>,
2211 fn check_substs_compatible_inner<'tcx>(
2213 generics: &'tcx ty::Generics,
2214 args: &'tcx [ty::GenericArg<'tcx>],
2216 if generics.count() != args.len() {
2220 let (parent_args, own_args) = args.split_at(generics.parent_count);
2222 if let Some(parent) = generics.parent
2223 && let parent_generics = tcx.generics_of(parent)
2224 && !check_substs_compatible_inner(tcx, parent_generics, parent_args) {
2228 for (param, arg) in std::iter::zip(&generics.params, own_args) {
2229 match (¶m.kind, arg.unpack()) {
2230 (ty::GenericParamDefKind::Type { .. }, ty::GenericArgKind::Type(_))
2231 | (ty::GenericParamDefKind::Lifetime, ty::GenericArgKind::Lifetime(_))
2232 | (ty::GenericParamDefKind::Const { .. }, ty::GenericArgKind::Const(_)) => {}
2240 let generics = tcx.generics_of(assoc_item.def_id);
2241 // Chop off any additional substs (RPITIT) substs
2242 let substs = &substs[0..generics.count().min(substs.len())];
2243 check_substs_compatible_inner(tcx, generics, substs)
2246 fn confirm_impl_trait_in_trait_candidate<'tcx>(
2247 selcx: &mut SelectionContext<'_, 'tcx>,
2248 obligation: &ProjectionTyObligation<'tcx>,
2249 data: ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>>,
2250 ) -> Progress<'tcx> {
2251 let tcx = selcx.tcx();
2252 let mut obligations = data.nested;
2254 let trait_fn_def_id = tcx.impl_trait_in_trait_parent(obligation.predicate.item_def_id);
2255 let Ok(leaf_def) = assoc_def(selcx, data.impl_def_id, trait_fn_def_id) else {
2256 return Progress { term: tcx.ty_error().into(), obligations };
2258 if !leaf_def.item.defaultness(tcx).has_value() {
2259 return Progress { term: tcx.ty_error().into(), obligations };
2262 // Use the default `impl Trait` for the trait, e.g., for a default trait body
2263 if leaf_def.item.container == ty::AssocItemContainer::TraitContainer {
2266 .mk_opaque(obligation.predicate.item_def_id, obligation.predicate.substs)
2272 // Rebase from {trait}::{fn}::{opaque} to {impl}::{fn}::{opaque},
2273 // since `data.substs` are the impl substs.
2274 let impl_fn_substs =
2275 obligation.predicate.substs.rebase_onto(tcx, tcx.parent(trait_fn_def_id), data.substs);
2276 let impl_fn_substs = translate_substs(
2278 obligation.param_env,
2281 leaf_def.defining_node,
2284 if !check_substs_compatible(tcx, &leaf_def.item, impl_fn_substs) {
2285 let err = tcx.ty_error_with_message(
2286 obligation.cause.span,
2287 "impl method and trait method have different parameters",
2289 return Progress { term: err.into(), obligations };
2292 let impl_fn_def_id = leaf_def.item.def_id;
2294 let cause = ObligationCause::new(
2295 obligation.cause.span,
2296 obligation.cause.body_id,
2297 super::ItemObligation(impl_fn_def_id),
2299 let predicates = normalize_with_depth_to(
2301 obligation.param_env,
2303 obligation.recursion_depth + 1,
2304 tcx.predicates_of(impl_fn_def_id).instantiate(tcx, impl_fn_substs),
2307 obligations.extend(std::iter::zip(predicates.predicates, predicates.spans).map(
2309 Obligation::with_depth(
2311 ObligationCause::new(
2312 obligation.cause.span,
2313 obligation.cause.body_id,
2314 if span.is_dummy() {
2315 super::ItemObligation(impl_fn_def_id)
2317 super::BindingObligation(impl_fn_def_id, span)
2320 obligation.recursion_depth + 1,
2321 obligation.param_env,
2327 let ty = super::normalize_to(
2329 obligation.param_env,
2331 tcx.bound_trait_impl_trait_tys(impl_fn_def_id)
2333 tys.map_or_else(|_| tcx.ty_error(), |tys| tys[&obligation.predicate.item_def_id])
2335 .subst(tcx, impl_fn_substs),
2339 Progress { term: ty.into(), obligations }
2342 // Get obligations corresponding to the predicates from the where-clause of the
2343 // associated type itself.
2344 fn assoc_ty_own_obligations<'cx, 'tcx>(
2345 selcx: &mut SelectionContext<'cx, 'tcx>,
2346 obligation: &ProjectionTyObligation<'tcx>,
2347 nested: &mut Vec<PredicateObligation<'tcx>>,
2349 let tcx = selcx.tcx();
2350 for predicate in tcx
2351 .predicates_of(obligation.predicate.item_def_id)
2352 .instantiate_own(tcx, obligation.predicate.substs)
2355 let normalized = normalize_with_depth_to(
2357 obligation.param_env,
2358 obligation.cause.clone(),
2359 obligation.recursion_depth + 1,
2363 nested.push(Obligation::with_depth(
2365 obligation.cause.clone(),
2366 obligation.recursion_depth + 1,
2367 obligation.param_env,
2373 /// Locate the definition of an associated type in the specialization hierarchy,
2374 /// starting from the given impl.
2376 /// Based on the "projection mode", this lookup may in fact only examine the
2377 /// topmost impl. See the comments for `Reveal` for more details.
2379 selcx: &SelectionContext<'_, '_>,
2381 assoc_def_id: DefId,
2382 ) -> Result<specialization_graph::LeafDef, ErrorGuaranteed> {
2383 let tcx = selcx.tcx();
2384 let trait_def_id = tcx.impl_trait_ref(impl_def_id).unwrap().def_id;
2385 let trait_def = tcx.trait_def(trait_def_id);
2387 // This function may be called while we are still building the
2388 // specialization graph that is queried below (via TraitDef::ancestors()),
2389 // so, in order to avoid unnecessary infinite recursion, we manually look
2390 // for the associated item at the given impl.
2391 // If there is no such item in that impl, this function will fail with a
2392 // cycle error if the specialization graph is currently being built.
2393 if let Some(&impl_item_id) = tcx.impl_item_implementor_ids(impl_def_id).get(&assoc_def_id) {
2394 let item = tcx.associated_item(impl_item_id);
2395 let impl_node = specialization_graph::Node::Impl(impl_def_id);
2396 return Ok(specialization_graph::LeafDef {
2398 defining_node: impl_node,
2399 finalizing_node: if item.defaultness(tcx).is_default() {
2407 let ancestors = trait_def.ancestors(tcx, impl_def_id)?;
2408 if let Some(assoc_item) = ancestors.leaf_def(tcx, assoc_def_id) {
2411 // This is saying that neither the trait nor
2412 // the impl contain a definition for this
2413 // associated type. Normally this situation
2414 // could only arise through a compiler bug --
2415 // if the user wrote a bad item name, it
2416 // should have failed in astconv.
2418 "No associated type `{}` for {}",
2419 tcx.item_name(assoc_def_id),
2420 tcx.def_path_str(impl_def_id)
2425 pub(crate) trait ProjectionCacheKeyExt<'cx, 'tcx>: Sized {
2426 fn from_poly_projection_predicate(
2427 selcx: &mut SelectionContext<'cx, 'tcx>,
2428 predicate: ty::PolyProjectionPredicate<'tcx>,
2432 impl<'cx, 'tcx> ProjectionCacheKeyExt<'cx, 'tcx> for ProjectionCacheKey<'tcx> {
2433 fn from_poly_projection_predicate(
2434 selcx: &mut SelectionContext<'cx, 'tcx>,
2435 predicate: ty::PolyProjectionPredicate<'tcx>,
2437 let infcx = selcx.infcx;
2438 // We don't do cross-snapshot caching of obligations with escaping regions,
2439 // so there's no cache key to use
2440 predicate.no_bound_vars().map(|predicate| {
2441 ProjectionCacheKey::new(
2442 // We don't attempt to match up with a specific type-variable state
2443 // from a specific call to `opt_normalize_projection_type` - if
2444 // there's no precise match, the original cache entry is "stranded"
2446 infcx.resolve_vars_if_possible(predicate.projection_ty),