1 //! Code for projecting associated types out of trait references.
3 use super::specialization_graph;
4 use super::translate_substs;
6 use super::MismatchedProjectionTypes;
8 use super::ObligationCause;
9 use super::PredicateObligation;
11 use super::SelectionContext;
12 use super::SelectionError;
14 ImplSourceClosureData, ImplSourceDiscriminantKindData, ImplSourceFnPointerData,
15 ImplSourceGeneratorData, ImplSourcePointeeData, ImplSourceUserDefinedData,
17 use super::{Normalized, NormalizedTy, ProjectionCacheEntry, ProjectionCacheKey};
19 use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
20 use crate::infer::{InferCtxt, InferOk, LateBoundRegionConversionTime};
21 use crate::traits::error_reporting::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_middle::traits::select::OverflowError;
32 use rustc_middle::ty::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable};
33 use rustc_middle::ty::visit::{MaxUniverse, TypeVisitable};
34 use rustc_middle::ty::DefIdTree;
35 use rustc_middle::ty::{self, Term, ToPredicate, Ty, TyCtxt};
36 use rustc_span::symbol::sym;
38 use std::collections::BTreeMap;
40 pub use rustc_middle::traits::Reveal;
42 pub type PolyProjectionObligation<'tcx> = Obligation<'tcx, ty::PolyProjectionPredicate<'tcx>>;
44 pub type ProjectionObligation<'tcx> = Obligation<'tcx, ty::ProjectionPredicate<'tcx>>;
46 pub type ProjectionTyObligation<'tcx> = Obligation<'tcx, ty::ProjectionTy<'tcx>>;
48 pub(super) struct InProgress;
50 /// When attempting to resolve `<T as TraitRef>::Name` ...
52 pub enum ProjectionError<'tcx> {
53 /// ...we found multiple sources of information and couldn't resolve the ambiguity.
56 /// ...an error occurred matching `T : TraitRef`
57 TraitSelectionError(SelectionError<'tcx>),
60 #[derive(PartialEq, Eq, Debug)]
61 enum ProjectionCandidate<'tcx> {
62 /// From a where-clause in the env or object type
63 ParamEnv(ty::PolyProjectionPredicate<'tcx>),
65 /// From the definition of `Trait` when you have something like <<A as Trait>::B as Trait2>::C
66 TraitDef(ty::PolyProjectionPredicate<'tcx>),
68 /// Bounds specified on an object type
69 Object(ty::PolyProjectionPredicate<'tcx>),
71 /// From an "impl" (or a "pseudo-impl" returned by select)
72 Select(Selection<'tcx>),
74 ImplTraitInTrait(ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>>),
77 enum ProjectionCandidateSet<'tcx> {
79 Single(ProjectionCandidate<'tcx>),
81 Error(SelectionError<'tcx>),
84 impl<'tcx> ProjectionCandidateSet<'tcx> {
85 fn mark_ambiguous(&mut self) {
86 *self = ProjectionCandidateSet::Ambiguous;
89 fn mark_error(&mut self, err: SelectionError<'tcx>) {
90 *self = ProjectionCandidateSet::Error(err);
93 // Returns true if the push was successful, or false if the candidate
94 // was discarded -- this could be because of ambiguity, or because
95 // a higher-priority candidate is already there.
96 fn push_candidate(&mut self, candidate: ProjectionCandidate<'tcx>) -> bool {
97 use self::ProjectionCandidate::*;
98 use self::ProjectionCandidateSet::*;
100 // This wacky variable is just used to try and
101 // make code readable and avoid confusing paths.
102 // It is assigned a "value" of `()` only on those
103 // paths in which we wish to convert `*self` to
104 // ambiguous (and return false, because the candidate
105 // was not used). On other paths, it is not assigned,
106 // and hence if those paths *could* reach the code that
107 // comes after the match, this fn would not compile.
108 let convert_to_ambiguous;
112 *self = Single(candidate);
117 // Duplicates can happen inside ParamEnv. In the case, we
118 // perform a lazy deduplication.
119 if current == &candidate {
123 // Prefer where-clauses. As in select, if there are multiple
124 // candidates, we prefer where-clause candidates over impls. This
125 // may seem a bit surprising, since impls are the source of
126 // "truth" in some sense, but in fact some of the impls that SEEM
127 // applicable are not, because of nested obligations. Where
128 // clauses are the safer choice. See the comment on
129 // `select::SelectionCandidate` and #21974 for more details.
130 match (current, candidate) {
131 (ParamEnv(..), ParamEnv(..)) => convert_to_ambiguous = (),
132 (ParamEnv(..), _) => return false,
133 (_, ParamEnv(..)) => unreachable!(),
134 (_, _) => convert_to_ambiguous = (),
138 Ambiguous | Error(..) => {
143 // We only ever get here when we moved from a single candidate
145 let () = convert_to_ambiguous;
151 /// States returned from `poly_project_and_unify_type`. Takes the place
152 /// of the old return type, which was:
153 /// ```ignore (not-rust)
155 /// Result<Option<Vec<PredicateObligation<'tcx>>>, InProgress>,
156 /// MismatchedProjectionTypes<'tcx>,
159 pub(super) enum ProjectAndUnifyResult<'tcx> {
160 /// The projection bound holds subject to the given obligations. If the
161 /// projection cannot be normalized because the required trait bound does
162 /// not hold, this is returned, with `obligations` being a predicate that
163 /// cannot be proven.
164 Holds(Vec<PredicateObligation<'tcx>>),
165 /// The projection cannot be normalized due to ambiguity. Resolving some
166 /// inference variables in the projection may fix this.
168 /// The project cannot be normalized because `poly_project_and_unify_type`
169 /// is called recursively while normalizing the same projection.
171 // the projection can be normalized, but is not equal to the expected type.
172 // Returns the type error that arose from the mismatch.
173 MismatchedProjectionTypes(MismatchedProjectionTypes<'tcx>),
176 /// Evaluates constraints of the form:
177 /// ```ignore (not-rust)
178 /// for<...> <T as Trait>::U == V
180 /// If successful, this may result in additional obligations. Also returns
181 /// the projection cache key used to track these additional obligations.
182 #[instrument(level = "debug", skip(selcx))]
183 pub(super) fn poly_project_and_unify_type<'cx, 'tcx>(
184 selcx: &mut SelectionContext<'cx, 'tcx>,
185 obligation: &PolyProjectionObligation<'tcx>,
186 ) -> ProjectAndUnifyResult<'tcx> {
187 let infcx = selcx.infcx();
188 let r = infcx.commit_if_ok(|_snapshot| {
189 let old_universe = infcx.universe();
190 let placeholder_predicate =
191 infcx.replace_bound_vars_with_placeholders(obligation.predicate);
192 let new_universe = infcx.universe();
194 let placeholder_obligation = obligation.with(placeholder_predicate);
195 match project_and_unify_type(selcx, &placeholder_obligation) {
196 ProjectAndUnifyResult::MismatchedProjectionTypes(e) => Err(e),
197 ProjectAndUnifyResult::Holds(obligations)
198 if old_universe != new_universe
199 && selcx.tcx().features().generic_associated_types_extended =>
201 // If the `generic_associated_types_extended` feature is active, then we ignore any
202 // obligations references lifetimes from any universe greater than or equal to the
203 // universe just created. Otherwise, we can end up with something like `for<'a> I: 'a`,
204 // which isn't quite what we want. Ideally, we want either an implied
205 // `for<'a where I: 'a> I: 'a` or we want to "lazily" check these hold when we
206 // substitute concrete regions. There is design work to be done here; until then,
207 // however, this allows experimenting potential GAT features without running into
208 // well-formedness issues.
209 let new_obligations = obligations
211 .filter(|obligation| {
212 let mut visitor = MaxUniverse::new();
213 obligation.predicate.visit_with(&mut visitor);
214 visitor.max_universe() < new_universe
217 Ok(ProjectAndUnifyResult::Holds(new_obligations))
225 Err(err) => ProjectAndUnifyResult::MismatchedProjectionTypes(err),
229 /// Evaluates constraints of the form:
230 /// ```ignore (not-rust)
231 /// <T as Trait>::U == V
233 /// If successful, this may result in additional obligations.
235 /// See [poly_project_and_unify_type] for an explanation of the return value.
236 #[instrument(level = "debug", skip(selcx))]
237 fn project_and_unify_type<'cx, 'tcx>(
238 selcx: &mut SelectionContext<'cx, 'tcx>,
239 obligation: &ProjectionObligation<'tcx>,
240 ) -> ProjectAndUnifyResult<'tcx> {
241 let mut obligations = vec![];
243 let infcx = selcx.infcx();
244 let normalized = match opt_normalize_projection_type(
246 obligation.param_env,
247 obligation.predicate.projection_ty,
248 obligation.cause.clone(),
249 obligation.recursion_depth,
253 Ok(None) => return ProjectAndUnifyResult::FailedNormalization,
254 Err(InProgress) => return ProjectAndUnifyResult::Recursive,
256 debug!(?normalized, ?obligations, "project_and_unify_type result");
257 let actual = obligation.predicate.term;
258 // For an example where this is neccessary see src/test/ui/impl-trait/nested-return-type2.rs
259 // This allows users to omit re-mentioning all bounds on an associated type and just use an
260 // `impl Trait` for the assoc type to add more bounds.
261 let InferOk { value: actual, obligations: new } =
262 selcx.infcx().replace_opaque_types_with_inference_vars(
264 obligation.cause.body_id,
265 obligation.cause.span,
266 obligation.param_env,
268 obligations.extend(new);
270 match infcx.at(&obligation.cause, obligation.param_env).eq(normalized, actual) {
271 Ok(InferOk { obligations: inferred_obligations, value: () }) => {
272 obligations.extend(inferred_obligations);
273 ProjectAndUnifyResult::Holds(obligations)
276 debug!("equating types encountered error {:?}", err);
277 ProjectAndUnifyResult::MismatchedProjectionTypes(MismatchedProjectionTypes { err })
282 /// Normalizes any associated type projections in `value`, replacing
283 /// them with a fully resolved type where possible. The return value
284 /// combines the normalized result and any additional obligations that
285 /// were incurred as result.
286 pub fn normalize<'a, 'b, 'tcx, T>(
287 selcx: &'a mut SelectionContext<'b, 'tcx>,
288 param_env: ty::ParamEnv<'tcx>,
289 cause: ObligationCause<'tcx>,
291 ) -> Normalized<'tcx, T>
293 T: TypeFoldable<'tcx>,
295 let mut obligations = Vec::new();
296 let value = normalize_to(selcx, param_env, cause, value, &mut obligations);
297 Normalized { value, obligations }
300 pub fn normalize_to<'a, 'b, 'tcx, T>(
301 selcx: &'a mut SelectionContext<'b, 'tcx>,
302 param_env: ty::ParamEnv<'tcx>,
303 cause: ObligationCause<'tcx>,
305 obligations: &mut Vec<PredicateObligation<'tcx>>,
308 T: TypeFoldable<'tcx>,
310 normalize_with_depth_to(selcx, param_env, cause, 0, value, obligations)
313 /// As `normalize`, but with a custom depth.
314 pub fn normalize_with_depth<'a, 'b, 'tcx, T>(
315 selcx: &'a mut SelectionContext<'b, 'tcx>,
316 param_env: ty::ParamEnv<'tcx>,
317 cause: ObligationCause<'tcx>,
320 ) -> Normalized<'tcx, T>
322 T: TypeFoldable<'tcx>,
324 let mut obligations = Vec::new();
325 let value = normalize_with_depth_to(selcx, param_env, cause, depth, value, &mut obligations);
326 Normalized { value, obligations }
329 #[instrument(level = "info", skip(selcx, param_env, cause, obligations))]
330 pub fn normalize_with_depth_to<'a, 'b, 'tcx, T>(
331 selcx: &'a mut SelectionContext<'b, 'tcx>,
332 param_env: ty::ParamEnv<'tcx>,
333 cause: ObligationCause<'tcx>,
336 obligations: &mut Vec<PredicateObligation<'tcx>>,
339 T: TypeFoldable<'tcx>,
341 debug!(obligations.len = obligations.len());
342 let mut normalizer = AssocTypeNormalizer::new(selcx, param_env, cause, depth, obligations);
343 let result = ensure_sufficient_stack(|| normalizer.fold(value));
344 debug!(?result, obligations.len = normalizer.obligations.len());
345 debug!(?normalizer.obligations,);
349 #[instrument(level = "info", skip(selcx, param_env, cause, obligations))]
350 pub fn try_normalize_with_depth_to<'a, 'b, 'tcx, T>(
351 selcx: &'a mut SelectionContext<'b, 'tcx>,
352 param_env: ty::ParamEnv<'tcx>,
353 cause: ObligationCause<'tcx>,
356 obligations: &mut Vec<PredicateObligation<'tcx>>,
359 T: TypeFoldable<'tcx>,
361 debug!(obligations.len = obligations.len());
362 let mut normalizer = AssocTypeNormalizer::new_without_eager_inference_replacement(
369 let result = ensure_sufficient_stack(|| normalizer.fold(value));
370 debug!(?result, obligations.len = normalizer.obligations.len());
371 debug!(?normalizer.obligations,);
375 pub(crate) fn needs_normalization<'tcx, T: TypeVisitable<'tcx>>(value: &T, reveal: Reveal) -> bool {
377 Reveal::UserFacing => value
378 .has_type_flags(ty::TypeFlags::HAS_TY_PROJECTION | ty::TypeFlags::HAS_CT_PROJECTION),
379 Reveal::All => value.has_type_flags(
380 ty::TypeFlags::HAS_TY_PROJECTION
381 | ty::TypeFlags::HAS_TY_OPAQUE
382 | ty::TypeFlags::HAS_CT_PROJECTION,
387 struct AssocTypeNormalizer<'a, 'b, 'tcx> {
388 selcx: &'a mut SelectionContext<'b, 'tcx>,
389 param_env: ty::ParamEnv<'tcx>,
390 cause: ObligationCause<'tcx>,
391 obligations: &'a mut Vec<PredicateObligation<'tcx>>,
393 universes: Vec<Option<ty::UniverseIndex>>,
394 /// If true, when a projection is unable to be completed, an inference
395 /// variable will be created and an obligation registered to project to that
396 /// inference variable. Also, constants will be eagerly evaluated.
397 eager_inference_replacement: bool,
400 impl<'a, 'b, 'tcx> AssocTypeNormalizer<'a, 'b, 'tcx> {
402 selcx: &'a mut SelectionContext<'b, 'tcx>,
403 param_env: ty::ParamEnv<'tcx>,
404 cause: ObligationCause<'tcx>,
406 obligations: &'a mut Vec<PredicateObligation<'tcx>>,
407 ) -> AssocTypeNormalizer<'a, 'b, 'tcx> {
408 AssocTypeNormalizer {
415 eager_inference_replacement: true,
419 fn new_without_eager_inference_replacement(
420 selcx: &'a mut SelectionContext<'b, 'tcx>,
421 param_env: ty::ParamEnv<'tcx>,
422 cause: ObligationCause<'tcx>,
424 obligations: &'a mut Vec<PredicateObligation<'tcx>>,
425 ) -> AssocTypeNormalizer<'a, 'b, 'tcx> {
426 AssocTypeNormalizer {
433 eager_inference_replacement: false,
437 fn fold<T: TypeFoldable<'tcx>>(&mut self, value: T) -> T {
438 let value = self.selcx.infcx().resolve_vars_if_possible(value);
442 !value.has_escaping_bound_vars(),
443 "Normalizing {:?} without wrapping in a `Binder`",
447 if !needs_normalization(&value, self.param_env.reveal()) {
450 value.fold_with(self)
455 impl<'a, 'b, 'tcx> TypeFolder<'tcx> for AssocTypeNormalizer<'a, 'b, 'tcx> {
456 fn tcx<'c>(&'c self) -> TyCtxt<'tcx> {
460 fn fold_binder<T: TypeFoldable<'tcx>>(
462 t: ty::Binder<'tcx, T>,
463 ) -> ty::Binder<'tcx, T> {
464 self.universes.push(None);
465 let t = t.super_fold_with(self);
466 self.universes.pop();
470 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
471 if !needs_normalization(&ty, self.param_env.reveal()) {
475 // We try to be a little clever here as a performance optimization in
476 // cases where there are nested projections under binders.
479 // for<'a> fn(<T as Foo>::One<'a, Box<dyn Bar<'a, Item=<T as Foo>::Two<'a>>>>)
481 // We normalize the substs on the projection before the projecting, but
482 // if we're naive, we'll
483 // replace bound vars on inner, project inner, replace placeholders on inner,
484 // replace bound vars on outer, project outer, replace placeholders on outer
486 // However, if we're a bit more clever, we can replace the bound vars
487 // on the entire type before normalizing nested projections, meaning we
488 // replace bound vars on outer, project inner,
489 // project outer, replace placeholders on outer
491 // This is possible because the inner `'a` will already be a placeholder
492 // when we need to normalize the inner projection
494 // On the other hand, this does add a bit of complexity, since we only
495 // replace bound vars if the current type is a `Projection` and we need
496 // to make sure we don't forget to fold the substs regardless.
499 // This is really important. While we *can* handle this, this has
500 // severe performance implications for large opaque types with
501 // late-bound regions. See `issue-88862` benchmark.
502 ty::Opaque(def_id, substs) => {
503 // Only normalize `impl Trait` outside of type inference, usually in codegen.
504 match self.param_env.reveal() {
505 Reveal::UserFacing => ty.super_fold_with(self),
508 let recursion_limit = self.tcx().recursion_limit();
509 if !recursion_limit.value_within_limit(self.depth) {
510 let obligation = Obligation::with_depth(
516 self.selcx.infcx().err_ctxt().report_overflow_error(&obligation, true);
519 let substs = substs.fold_with(self);
520 let generic_ty = self.tcx().bound_type_of(def_id);
521 let concrete_ty = generic_ty.subst(self.tcx(), substs);
523 let folded_ty = self.fold_ty(concrete_ty);
530 ty::Projection(data) if !data.has_escaping_bound_vars() => {
531 // This branch is *mostly* just an optimization: when we don't
532 // have escaping bound vars, we don't need to replace them with
533 // placeholders (see branch below). *Also*, we know that we can
534 // register an obligation to *later* project, since we know
535 // there won't be bound vars there.
536 let data = data.fold_with(self);
537 let normalized_ty = if self.eager_inference_replacement {
538 normalize_projection_type(
544 &mut self.obligations,
547 opt_normalize_projection_type(
553 &mut self.obligations,
557 .unwrap_or_else(|| ty.super_fold_with(self).into())
559 // For cases like #95134 we would like to catch overflows early
560 // otherwise they slip away away and cause ICE.
561 let recursion_limit = self.tcx().recursion_limit();
562 if !recursion_limit.value_within_limit(self.depth)
563 // HACK: Don't overflow when running cargo doc see #100991
564 && !self.tcx().sess.opts.actually_rustdoc
566 let obligation = Obligation::with_depth(
572 self.selcx.infcx().err_ctxt().report_overflow_error(&obligation, true);
578 obligations.len = ?self.obligations.len(),
579 "AssocTypeNormalizer: normalized type"
581 normalized_ty.ty().unwrap()
584 ty::Projection(data) => {
585 // If there are escaping bound vars, we temporarily replace the
586 // bound vars with placeholders. Note though, that in the case
587 // that we still can't project for whatever reason (e.g. self
588 // type isn't known enough), we *can't* register an obligation
589 // and return an inference variable (since then that obligation
590 // would have bound vars and that's a can of worms). Instead,
591 // we just give up and fall back to pretending like we never tried!
593 // Note: this isn't necessarily the final approach here; we may
594 // want to figure out how to register obligations with escaping vars
595 // or handle this some other way.
597 let infcx = self.selcx.infcx();
598 let (data, mapped_regions, mapped_types, mapped_consts) =
599 BoundVarReplacer::replace_bound_vars(infcx, &mut self.universes, data);
600 let data = data.fold_with(self);
601 let normalized_ty = opt_normalize_projection_type(
607 &mut self.obligations,
611 .map(|term| term.ty().unwrap())
612 .map(|normalized_ty| {
613 PlaceholderReplacer::replace_placeholders(
622 .unwrap_or_else(|| ty.super_fold_with(self));
628 obligations.len = ?self.obligations.len(),
629 "AssocTypeNormalizer: normalized type"
634 _ => ty.super_fold_with(self),
638 #[instrument(skip(self), level = "debug")]
639 fn fold_const(&mut self, constant: ty::Const<'tcx>) -> ty::Const<'tcx> {
640 let tcx = self.selcx.tcx();
641 if tcx.lazy_normalization() {
644 let constant = constant.super_fold_with(self);
645 debug!(?constant, ?self.param_env);
646 with_replaced_escaping_bound_vars(
650 |constant| constant.eval(tcx, self.param_env),
656 fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
657 if p.allow_normalization() && needs_normalization(&p, self.param_env.reveal()) {
658 p.super_fold_with(self)
665 pub struct BoundVarReplacer<'me, 'tcx> {
666 infcx: &'me InferCtxt<'tcx>,
667 // These three maps track the bound variable that were replaced by placeholders. It might be
668 // nice to remove these since we already have the `kind` in the placeholder; we really just need
669 // the `var` (but we *could* bring that into scope if we were to track them as we pass them).
670 mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
671 mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy>,
672 mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
673 // The current depth relative to *this* folding, *not* the entire normalization. In other words,
674 // the depth of binders we've passed here.
675 current_index: ty::DebruijnIndex,
676 // The `UniverseIndex` of the binding levels above us. These are optional, since we are lazy:
677 // we don't actually create a universe until we see a bound var we have to replace.
678 universe_indices: &'me mut Vec<Option<ty::UniverseIndex>>,
681 /// Executes `f` on `value` after replacing all escaping bound variables with placeholders
682 /// and then replaces these placeholders with the original bound variables in the result.
684 /// In most places, bound variables should be replaced right when entering a binder, making
685 /// this function unnecessary. However, normalization currently does not do that, so we have
686 /// to do this lazily.
688 /// You should not add any additional uses of this function, at least not without first
689 /// discussing it with t-types.
691 /// FIXME(@lcnr): We may even consider experimenting with eagerly replacing bound vars during
692 /// normalization as well, at which point this function will be unnecessary and can be removed.
693 pub fn with_replaced_escaping_bound_vars<'a, 'tcx, T: TypeFoldable<'tcx>, R: TypeFoldable<'tcx>>(
694 infcx: &'a InferCtxt<'tcx>,
695 universe_indices: &'a mut Vec<Option<ty::UniverseIndex>>,
697 f: impl FnOnce(T) -> R,
699 if value.has_escaping_bound_vars() {
700 let (value, mapped_regions, mapped_types, mapped_consts) =
701 BoundVarReplacer::replace_bound_vars(infcx, universe_indices, value);
702 let result = f(value);
703 PlaceholderReplacer::replace_placeholders(
716 impl<'me, 'tcx> BoundVarReplacer<'me, 'tcx> {
717 /// Returns `Some` if we *were* able to replace bound vars. If there are any bound vars that
718 /// use a binding level above `universe_indices.len()`, we fail.
719 pub fn replace_bound_vars<T: TypeFoldable<'tcx>>(
720 infcx: &'me InferCtxt<'tcx>,
721 universe_indices: &'me mut Vec<Option<ty::UniverseIndex>>,
725 BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
726 BTreeMap<ty::PlaceholderType, ty::BoundTy>,
727 BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
729 let mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion> = BTreeMap::new();
730 let mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy> = BTreeMap::new();
731 let mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar> = BTreeMap::new();
733 let mut replacer = BoundVarReplacer {
738 current_index: ty::INNERMOST,
742 let value = value.fold_with(&mut replacer);
744 (value, replacer.mapped_regions, replacer.mapped_types, replacer.mapped_consts)
747 fn universe_for(&mut self, debruijn: ty::DebruijnIndex) -> ty::UniverseIndex {
748 let infcx = self.infcx;
750 self.universe_indices.len() + self.current_index.as_usize() - debruijn.as_usize() - 1;
751 let universe = self.universe_indices[index].unwrap_or_else(|| {
752 for i in self.universe_indices.iter_mut().take(index + 1) {
753 *i = i.or_else(|| Some(infcx.create_next_universe()))
755 self.universe_indices[index].unwrap()
761 impl<'tcx> TypeFolder<'tcx> for BoundVarReplacer<'_, 'tcx> {
762 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
766 fn fold_binder<T: TypeFoldable<'tcx>>(
768 t: ty::Binder<'tcx, T>,
769 ) -> ty::Binder<'tcx, T> {
770 self.current_index.shift_in(1);
771 let t = t.super_fold_with(self);
772 self.current_index.shift_out(1);
776 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
778 ty::ReLateBound(debruijn, _)
779 if debruijn.as_usize() + 1
780 > self.current_index.as_usize() + self.universe_indices.len() =>
782 bug!("Bound vars outside of `self.universe_indices`");
784 ty::ReLateBound(debruijn, br) if debruijn >= self.current_index => {
785 let universe = self.universe_for(debruijn);
786 let p = ty::PlaceholderRegion { universe, name: br.kind };
787 self.mapped_regions.insert(p, br);
788 self.infcx.tcx.mk_region(ty::RePlaceholder(p))
794 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
796 ty::Bound(debruijn, _)
797 if debruijn.as_usize() + 1
798 > self.current_index.as_usize() + self.universe_indices.len() =>
800 bug!("Bound vars outside of `self.universe_indices`");
802 ty::Bound(debruijn, bound_ty) if debruijn >= self.current_index => {
803 let universe = self.universe_for(debruijn);
804 let p = ty::PlaceholderType { universe, name: bound_ty.var };
805 self.mapped_types.insert(p, bound_ty);
806 self.infcx.tcx.mk_ty(ty::Placeholder(p))
808 _ if t.has_vars_bound_at_or_above(self.current_index) => t.super_fold_with(self),
813 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
815 ty::ConstKind::Bound(debruijn, _)
816 if debruijn.as_usize() + 1
817 > self.current_index.as_usize() + self.universe_indices.len() =>
819 bug!("Bound vars outside of `self.universe_indices`");
821 ty::ConstKind::Bound(debruijn, bound_const) if debruijn >= self.current_index => {
822 let universe = self.universe_for(debruijn);
823 let p = ty::PlaceholderConst { universe, name: bound_const };
824 self.mapped_consts.insert(p, bound_const);
827 .mk_const(ty::ConstS { kind: ty::ConstKind::Placeholder(p), ty: ct.ty() })
829 _ => ct.super_fold_with(self),
833 fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
834 if p.has_vars_bound_at_or_above(self.current_index) { p.super_fold_with(self) } else { p }
838 // The inverse of `BoundVarReplacer`: replaces placeholders with the bound vars from which they came.
839 pub struct PlaceholderReplacer<'me, 'tcx> {
840 infcx: &'me InferCtxt<'tcx>,
841 mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
842 mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy>,
843 mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
844 universe_indices: &'me [Option<ty::UniverseIndex>],
845 current_index: ty::DebruijnIndex,
848 impl<'me, 'tcx> PlaceholderReplacer<'me, 'tcx> {
849 pub fn replace_placeholders<T: TypeFoldable<'tcx>>(
850 infcx: &'me InferCtxt<'tcx>,
851 mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
852 mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy>,
853 mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
854 universe_indices: &'me [Option<ty::UniverseIndex>],
857 let mut replacer = PlaceholderReplacer {
863 current_index: ty::INNERMOST,
865 value.fold_with(&mut replacer)
869 impl<'tcx> TypeFolder<'tcx> for PlaceholderReplacer<'_, 'tcx> {
870 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
874 fn fold_binder<T: TypeFoldable<'tcx>>(
876 t: ty::Binder<'tcx, T>,
877 ) -> ty::Binder<'tcx, T> {
878 if !t.has_placeholders() && !t.has_infer_regions() {
881 self.current_index.shift_in(1);
882 let t = t.super_fold_with(self);
883 self.current_index.shift_out(1);
887 fn fold_region(&mut self, r0: ty::Region<'tcx>) -> ty::Region<'tcx> {
893 .unwrap_region_constraints()
894 .opportunistic_resolve_region(self.infcx.tcx, r0),
899 ty::RePlaceholder(p) => {
900 let replace_var = self.mapped_regions.get(&p);
902 Some(replace_var) => {
906 .position(|u| matches!(u, Some(pu) if *pu == p.universe))
907 .unwrap_or_else(|| bug!("Unexpected placeholder universe."));
908 let db = ty::DebruijnIndex::from_usize(
909 self.universe_indices.len() - index + self.current_index.as_usize() - 1,
911 self.tcx().mk_region(ty::ReLateBound(db, *replace_var))
919 debug!(?r0, ?r1, ?r2, "fold_region");
924 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
926 ty::Placeholder(p) => {
927 let replace_var = self.mapped_types.get(&p);
929 Some(replace_var) => {
933 .position(|u| matches!(u, Some(pu) if *pu == p.universe))
934 .unwrap_or_else(|| bug!("Unexpected placeholder universe."));
935 let db = ty::DebruijnIndex::from_usize(
936 self.universe_indices.len() - index + self.current_index.as_usize() - 1,
938 self.tcx().mk_ty(ty::Bound(db, *replace_var))
944 _ if ty.has_placeholders() || ty.has_infer_regions() => ty.super_fold_with(self),
949 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
950 if let ty::ConstKind::Placeholder(p) = ct.kind() {
951 let replace_var = self.mapped_consts.get(&p);
953 Some(replace_var) => {
957 .position(|u| matches!(u, Some(pu) if *pu == p.universe))
958 .unwrap_or_else(|| bug!("Unexpected placeholder universe."));
959 let db = ty::DebruijnIndex::from_usize(
960 self.universe_indices.len() - index + self.current_index.as_usize() - 1,
962 self.tcx().mk_const(ty::ConstS {
963 kind: ty::ConstKind::Bound(db, *replace_var),
970 ct.super_fold_with(self)
975 /// The guts of `normalize`: normalize a specific projection like `<T
976 /// as Trait>::Item`. The result is always a type (and possibly
977 /// additional obligations). If ambiguity arises, which implies that
978 /// there are unresolved type variables in the projection, we will
979 /// substitute a fresh type variable `$X` and generate a new
980 /// obligation `<T as Trait>::Item == $X` for later.
981 pub fn normalize_projection_type<'a, 'b, 'tcx>(
982 selcx: &'a mut SelectionContext<'b, 'tcx>,
983 param_env: ty::ParamEnv<'tcx>,
984 projection_ty: ty::ProjectionTy<'tcx>,
985 cause: ObligationCause<'tcx>,
987 obligations: &mut Vec<PredicateObligation<'tcx>>,
989 opt_normalize_projection_type(
999 .unwrap_or_else(move || {
1000 // if we bottom out in ambiguity, create a type variable
1001 // and a deferred predicate to resolve this when more type
1002 // information is available.
1006 .infer_projection(param_env, projection_ty, cause, depth + 1, obligations)
1011 /// The guts of `normalize`: normalize a specific projection like `<T
1012 /// as Trait>::Item`. The result is always a type (and possibly
1013 /// additional obligations). Returns `None` in the case of ambiguity,
1014 /// which indicates that there are unbound type variables.
1016 /// This function used to return `Option<NormalizedTy<'tcx>>`, which contains a
1017 /// `Ty<'tcx>` and an obligations vector. But that obligation vector was very
1018 /// often immediately appended to another obligations vector. So now this
1019 /// function takes an obligations vector and appends to it directly, which is
1020 /// slightly uglier but avoids the need for an extra short-lived allocation.
1021 #[instrument(level = "debug", skip(selcx, param_env, cause, obligations))]
1022 fn opt_normalize_projection_type<'a, 'b, 'tcx>(
1023 selcx: &'a mut SelectionContext<'b, 'tcx>,
1024 param_env: ty::ParamEnv<'tcx>,
1025 projection_ty: ty::ProjectionTy<'tcx>,
1026 cause: ObligationCause<'tcx>,
1028 obligations: &mut Vec<PredicateObligation<'tcx>>,
1029 ) -> Result<Option<Term<'tcx>>, InProgress> {
1030 let infcx = selcx.infcx();
1031 // Don't use the projection cache in intercrate mode -
1032 // the `infcx` may be re-used between intercrate in non-intercrate
1033 // mode, which could lead to using incorrect cache results.
1034 let use_cache = !selcx.is_intercrate();
1036 let projection_ty = infcx.resolve_vars_if_possible(projection_ty);
1037 let cache_key = ProjectionCacheKey::new(projection_ty);
1039 // FIXME(#20304) For now, I am caching here, which is good, but it
1040 // means we don't capture the type variables that are created in
1041 // the case of ambiguity. Which means we may create a large stream
1042 // of such variables. OTOH, if we move the caching up a level, we
1043 // would not benefit from caching when proving `T: Trait<U=Foo>`
1044 // bounds. It might be the case that we want two distinct caches,
1045 // or else another kind of cache entry.
1047 let cache_result = if use_cache {
1048 infcx.inner.borrow_mut().projection_cache().try_start(cache_key)
1052 match cache_result {
1053 Ok(()) => debug!("no cache"),
1054 Err(ProjectionCacheEntry::Ambiguous) => {
1055 // If we found ambiguity the last time, that means we will continue
1056 // to do so until some type in the key changes (and we know it
1057 // hasn't, because we just fully resolved it).
1058 debug!("found cache entry: ambiguous");
1061 Err(ProjectionCacheEntry::InProgress) => {
1062 // Under lazy normalization, this can arise when
1063 // bootstrapping. That is, imagine an environment with a
1064 // where-clause like `A::B == u32`. Now, if we are asked
1065 // to normalize `A::B`, we will want to check the
1066 // where-clauses in scope. So we will try to unify `A::B`
1067 // with `A::B`, which can trigger a recursive
1070 debug!("found cache entry: in-progress");
1072 // Cache that normalizing this projection resulted in a cycle. This
1073 // should ensure that, unless this happens within a snapshot that's
1074 // rolled back, fulfillment or evaluation will notice the cycle.
1077 infcx.inner.borrow_mut().projection_cache().recur(cache_key);
1079 return Err(InProgress);
1081 Err(ProjectionCacheEntry::Recur) => {
1082 debug!("recur cache");
1083 return Err(InProgress);
1085 Err(ProjectionCacheEntry::NormalizedTy { ty, complete: _ }) => {
1086 // This is the hottest path in this function.
1088 // If we find the value in the cache, then return it along
1089 // with the obligations that went along with it. Note
1090 // that, when using a fulfillment context, these
1091 // obligations could in principle be ignored: they have
1092 // already been registered when the cache entry was
1093 // created (and hence the new ones will quickly be
1094 // discarded as duplicated). But when doing trait
1095 // evaluation this is not the case, and dropping the trait
1096 // evaluations can causes ICEs (e.g., #43132).
1097 debug!(?ty, "found normalized ty");
1098 obligations.extend(ty.obligations);
1099 return Ok(Some(ty.value));
1101 Err(ProjectionCacheEntry::Error) => {
1102 debug!("opt_normalize_projection_type: found error");
1103 let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth);
1104 obligations.extend(result.obligations);
1105 return Ok(Some(result.value.into()));
1109 let obligation = Obligation::with_depth(cause.clone(), depth, param_env, projection_ty);
1111 match project(selcx, &obligation) {
1112 Ok(Projected::Progress(Progress {
1113 term: projected_term,
1114 obligations: mut projected_obligations,
1116 // if projection succeeded, then what we get out of this
1117 // is also non-normalized (consider: it was derived from
1118 // an impl, where-clause etc) and hence we must
1121 let projected_term = selcx.infcx().resolve_vars_if_possible(projected_term);
1123 let mut result = if projected_term.has_projections() {
1124 let mut normalizer = AssocTypeNormalizer::new(
1129 &mut projected_obligations,
1131 let normalized_ty = normalizer.fold(projected_term);
1133 Normalized { value: normalized_ty, obligations: projected_obligations }
1135 Normalized { value: projected_term, obligations: projected_obligations }
1138 let mut deduped: SsoHashSet<_> = Default::default();
1139 result.obligations.drain_filter(|projected_obligation| {
1140 if !deduped.insert(projected_obligation.clone()) {
1147 infcx.inner.borrow_mut().projection_cache().insert_term(cache_key, result.clone());
1149 obligations.extend(result.obligations);
1150 Ok(Some(result.value))
1152 Ok(Projected::NoProgress(projected_ty)) => {
1153 let result = Normalized { value: projected_ty, obligations: vec![] };
1155 infcx.inner.borrow_mut().projection_cache().insert_term(cache_key, result.clone());
1157 // No need to extend `obligations`.
1158 Ok(Some(result.value))
1160 Err(ProjectionError::TooManyCandidates) => {
1161 debug!("opt_normalize_projection_type: too many candidates");
1163 infcx.inner.borrow_mut().projection_cache().ambiguous(cache_key);
1167 Err(ProjectionError::TraitSelectionError(_)) => {
1168 debug!("opt_normalize_projection_type: ERROR");
1169 // if we got an error processing the `T as Trait` part,
1170 // just return `ty::err` but add the obligation `T :
1171 // Trait`, which when processed will cause the error to be
1175 infcx.inner.borrow_mut().projection_cache().error(cache_key);
1177 let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth);
1178 obligations.extend(result.obligations);
1179 Ok(Some(result.value.into()))
1184 /// If we are projecting `<T as Trait>::Item`, but `T: Trait` does not
1185 /// hold. In various error cases, we cannot generate a valid
1186 /// normalized projection. Therefore, we create an inference variable
1187 /// return an associated obligation that, when fulfilled, will lead to
1190 /// Note that we used to return `Error` here, but that was quite
1191 /// dubious -- the premise was that an error would *eventually* be
1192 /// reported, when the obligation was processed. But in general once
1193 /// you see an `Error` you are supposed to be able to assume that an
1194 /// error *has been* reported, so that you can take whatever heuristic
1195 /// paths you want to take. To make things worse, it was possible for
1196 /// cycles to arise, where you basically had a setup like `<MyType<$0>
1197 /// as Trait>::Foo == $0`. Here, normalizing `<MyType<$0> as
1198 /// Trait>::Foo> to `[type error]` would lead to an obligation of
1199 /// `<MyType<[type error]> as Trait>::Foo`. We are supposed to report
1200 /// an error for this obligation, but we legitimately should not,
1201 /// because it contains `[type error]`. Yuck! (See issue #29857 for
1202 /// one case where this arose.)
1203 fn normalize_to_error<'a, 'tcx>(
1204 selcx: &mut SelectionContext<'a, 'tcx>,
1205 param_env: ty::ParamEnv<'tcx>,
1206 projection_ty: ty::ProjectionTy<'tcx>,
1207 cause: ObligationCause<'tcx>,
1209 ) -> NormalizedTy<'tcx> {
1210 let trait_ref = ty::Binder::dummy(projection_ty.trait_ref(selcx.tcx()));
1211 let trait_obligation = Obligation {
1213 recursion_depth: depth,
1215 predicate: trait_ref.without_const().to_predicate(selcx.tcx()),
1217 let tcx = selcx.infcx().tcx;
1218 let def_id = projection_ty.item_def_id;
1219 let new_value = selcx.infcx().next_ty_var(TypeVariableOrigin {
1220 kind: TypeVariableOriginKind::NormalizeProjectionType,
1221 span: tcx.def_span(def_id),
1223 Normalized { value: new_value, obligations: vec![trait_obligation] }
1226 enum Projected<'tcx> {
1227 Progress(Progress<'tcx>),
1228 NoProgress(ty::Term<'tcx>),
1231 struct Progress<'tcx> {
1232 term: ty::Term<'tcx>,
1233 obligations: Vec<PredicateObligation<'tcx>>,
1236 impl<'tcx> Progress<'tcx> {
1237 fn error(tcx: TyCtxt<'tcx>) -> Self {
1238 Progress { term: tcx.ty_error().into(), obligations: vec![] }
1241 fn with_addl_obligations(mut self, mut obligations: Vec<PredicateObligation<'tcx>>) -> Self {
1242 self.obligations.append(&mut obligations);
1247 /// Computes the result of a projection type (if we can).
1250 /// - `obligation` must be fully normalized
1251 #[instrument(level = "info", skip(selcx))]
1252 fn project<'cx, 'tcx>(
1253 selcx: &mut SelectionContext<'cx, 'tcx>,
1254 obligation: &ProjectionTyObligation<'tcx>,
1255 ) -> Result<Projected<'tcx>, ProjectionError<'tcx>> {
1256 if !selcx.tcx().recursion_limit().value_within_limit(obligation.recursion_depth) {
1257 // This should really be an immediate error, but some existing code
1258 // relies on being able to recover from this.
1259 return Err(ProjectionError::TraitSelectionError(SelectionError::Overflow(
1260 OverflowError::Canonical,
1264 if obligation.predicate.references_error() {
1265 return Ok(Projected::Progress(Progress::error(selcx.tcx())));
1268 let mut candidates = ProjectionCandidateSet::None;
1270 assemble_candidate_for_impl_trait_in_trait(selcx, obligation, &mut candidates);
1272 // Make sure that the following procedures are kept in order. ParamEnv
1273 // needs to be first because it has highest priority, and Select checks
1274 // the return value of push_candidate which assumes it's ran at last.
1275 assemble_candidates_from_param_env(selcx, obligation, &mut candidates);
1277 assemble_candidates_from_trait_def(selcx, obligation, &mut candidates);
1279 assemble_candidates_from_object_ty(selcx, obligation, &mut candidates);
1281 if let ProjectionCandidateSet::Single(ProjectionCandidate::Object(_)) = candidates {
1282 // Avoid normalization cycle from selection (see
1283 // `assemble_candidates_from_object_ty`).
1284 // FIXME(lazy_normalization): Lazy normalization should save us from
1285 // having to special case this.
1287 assemble_candidates_from_impls(selcx, obligation, &mut candidates);
1291 ProjectionCandidateSet::Single(candidate) => {
1292 Ok(Projected::Progress(confirm_candidate(selcx, obligation, candidate)))
1294 ProjectionCandidateSet::None => Ok(Projected::NoProgress(
1295 // FIXME(associated_const_generics): this may need to change in the future?
1296 // need to investigate whether or not this is fine.
1299 .mk_projection(obligation.predicate.item_def_id, obligation.predicate.substs)
1302 // Error occurred while trying to processing impls.
1303 ProjectionCandidateSet::Error(e) => Err(ProjectionError::TraitSelectionError(e)),
1304 // Inherent ambiguity that prevents us from even enumerating the
1306 ProjectionCandidateSet::Ambiguous => Err(ProjectionError::TooManyCandidates),
1310 /// If the predicate's item is an `ImplTraitPlaceholder`, we do a select on the
1311 /// corresponding trait ref. If this yields an `impl`, then we're able to project
1312 /// to a concrete type, since we have an `impl`'s method to provide the RPITIT.
1313 fn assemble_candidate_for_impl_trait_in_trait<'cx, 'tcx>(
1314 selcx: &mut SelectionContext<'cx, 'tcx>,
1315 obligation: &ProjectionTyObligation<'tcx>,
1316 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1318 let tcx = selcx.tcx();
1319 if tcx.def_kind(obligation.predicate.item_def_id) == DefKind::ImplTraitPlaceholder {
1320 let trait_fn_def_id = tcx.impl_trait_in_trait_parent(obligation.predicate.item_def_id);
1321 let trait_def_id = tcx.parent(trait_fn_def_id);
1323 obligation.predicate.substs.truncate_to(tcx, tcx.generics_of(trait_def_id));
1324 // FIXME(named-returns): Binders
1325 let trait_predicate =
1326 ty::Binder::dummy(ty::TraitRef { def_id: trait_def_id, substs: trait_substs })
1327 .to_poly_trait_predicate();
1330 selcx.infcx().commit_if_ok(|_| match selcx.select(&obligation.with(trait_predicate)) {
1331 Ok(Some(super::ImplSource::UserDefined(data))) => {
1332 candidate_set.push_candidate(ProjectionCandidate::ImplTraitInTrait(data));
1336 candidate_set.mark_ambiguous();
1340 // Don't know enough about the impl to provide a useful signature
1344 debug!(error = ?e, "selection error");
1345 candidate_set.mark_error(e);
1352 /// The first thing we have to do is scan through the parameter
1353 /// environment to see whether there are any projection predicates
1354 /// there that can answer this question.
1355 fn assemble_candidates_from_param_env<'cx, 'tcx>(
1356 selcx: &mut SelectionContext<'cx, 'tcx>,
1357 obligation: &ProjectionTyObligation<'tcx>,
1358 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1360 assemble_candidates_from_predicates(
1364 ProjectionCandidate::ParamEnv,
1365 obligation.param_env.caller_bounds().iter(),
1370 /// In the case of a nested projection like <<A as Foo>::FooT as Bar>::BarT, we may find
1371 /// that the definition of `Foo` has some clues:
1373 /// ```ignore (illustrative)
1375 /// type FooT : Bar<BarT=i32>
1379 /// Here, for example, we could conclude that the result is `i32`.
1380 fn assemble_candidates_from_trait_def<'cx, 'tcx>(
1381 selcx: &mut SelectionContext<'cx, 'tcx>,
1382 obligation: &ProjectionTyObligation<'tcx>,
1383 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1385 debug!("assemble_candidates_from_trait_def(..)");
1387 let tcx = selcx.tcx();
1388 // Check whether the self-type is itself a projection.
1389 // If so, extract what we know from the trait and try to come up with a good answer.
1390 let bounds = match *obligation.predicate.self_ty().kind() {
1391 ty::Projection(ref data) => tcx.bound_item_bounds(data.item_def_id).subst(tcx, data.substs),
1392 ty::Opaque(def_id, substs) => tcx.bound_item_bounds(def_id).subst(tcx, substs),
1393 ty::Infer(ty::TyVar(_)) => {
1394 // If the self-type is an inference variable, then it MAY wind up
1395 // being a projected type, so induce an ambiguity.
1396 candidate_set.mark_ambiguous();
1402 assemble_candidates_from_predicates(
1406 ProjectionCandidate::TraitDef,
1412 /// In the case of a trait object like
1413 /// `<dyn Iterator<Item = ()> as Iterator>::Item` we can use the existential
1414 /// predicate in the trait object.
1416 /// We don't go through the select candidate for these bounds to avoid cycles:
1417 /// In the above case, `dyn Iterator<Item = ()>: Iterator` would create a
1418 /// nested obligation of `<dyn Iterator<Item = ()> as Iterator>::Item: Sized`,
1419 /// this then has to be normalized without having to prove
1420 /// `dyn Iterator<Item = ()>: Iterator` again.
1421 fn assemble_candidates_from_object_ty<'cx, 'tcx>(
1422 selcx: &mut SelectionContext<'cx, 'tcx>,
1423 obligation: &ProjectionTyObligation<'tcx>,
1424 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1426 debug!("assemble_candidates_from_object_ty(..)");
1428 let tcx = selcx.tcx();
1430 let self_ty = obligation.predicate.self_ty();
1431 let object_ty = selcx.infcx().shallow_resolve(self_ty);
1432 let data = match object_ty.kind() {
1433 ty::Dynamic(data, ..) => data,
1434 ty::Infer(ty::TyVar(_)) => {
1435 // If the self-type is an inference variable, then it MAY wind up
1436 // being an object type, so induce an ambiguity.
1437 candidate_set.mark_ambiguous();
1442 let env_predicates = data
1443 .projection_bounds()
1444 .filter(|bound| bound.item_def_id() == obligation.predicate.item_def_id)
1445 .map(|p| p.with_self_ty(tcx, object_ty).to_predicate(tcx));
1447 assemble_candidates_from_predicates(
1451 ProjectionCandidate::Object,
1459 skip(selcx, candidate_set, ctor, env_predicates, potentially_unnormalized_candidates)
1461 fn assemble_candidates_from_predicates<'cx, 'tcx>(
1462 selcx: &mut SelectionContext<'cx, 'tcx>,
1463 obligation: &ProjectionTyObligation<'tcx>,
1464 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1465 ctor: fn(ty::PolyProjectionPredicate<'tcx>) -> ProjectionCandidate<'tcx>,
1466 env_predicates: impl Iterator<Item = ty::Predicate<'tcx>>,
1467 potentially_unnormalized_candidates: bool,
1469 let infcx = selcx.infcx();
1470 for predicate in env_predicates {
1471 let bound_predicate = predicate.kind();
1472 if let ty::PredicateKind::Projection(data) = predicate.kind().skip_binder() {
1473 let data = bound_predicate.rebind(data);
1474 if data.projection_def_id() != obligation.predicate.item_def_id {
1478 let is_match = infcx.probe(|_| {
1479 selcx.match_projection_projections(
1482 potentially_unnormalized_candidates,
1487 ProjectionMatchesProjection::Yes => {
1488 candidate_set.push_candidate(ctor(data));
1490 if potentially_unnormalized_candidates
1491 && !obligation.predicate.has_non_region_infer()
1493 // HACK: Pick the first trait def candidate for a fully
1494 // inferred predicate. This is to allow duplicates that
1495 // differ only in normalization.
1499 ProjectionMatchesProjection::Ambiguous => {
1500 candidate_set.mark_ambiguous();
1502 ProjectionMatchesProjection::No => {}
1508 #[instrument(level = "debug", skip(selcx, obligation, candidate_set))]
1509 fn assemble_candidates_from_impls<'cx, 'tcx>(
1510 selcx: &mut SelectionContext<'cx, 'tcx>,
1511 obligation: &ProjectionTyObligation<'tcx>,
1512 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1514 // Can't assemble candidate from impl for RPITIT
1515 if selcx.tcx().def_kind(obligation.predicate.item_def_id) == DefKind::ImplTraitPlaceholder {
1519 // If we are resolving `<T as TraitRef<...>>::Item == Type`,
1520 // start out by selecting the predicate `T as TraitRef<...>`:
1521 let poly_trait_ref = ty::Binder::dummy(obligation.predicate.trait_ref(selcx.tcx()));
1522 let trait_obligation = obligation.with(poly_trait_ref.to_poly_trait_predicate());
1523 let _ = selcx.infcx().commit_if_ok(|_| {
1524 let impl_source = match selcx.select(&trait_obligation) {
1525 Ok(Some(impl_source)) => impl_source,
1527 candidate_set.mark_ambiguous();
1531 debug!(error = ?e, "selection error");
1532 candidate_set.mark_error(e);
1537 let eligible = match &impl_source {
1538 super::ImplSource::Closure(_)
1539 | super::ImplSource::Generator(_)
1540 | super::ImplSource::FnPointer(_)
1541 | super::ImplSource::TraitAlias(_) => true,
1542 super::ImplSource::UserDefined(impl_data) => {
1543 // We have to be careful when projecting out of an
1544 // impl because of specialization. If we are not in
1545 // codegen (i.e., projection mode is not "any"), and the
1546 // impl's type is declared as default, then we disable
1547 // projection (even if the trait ref is fully
1548 // monomorphic). In the case where trait ref is not
1549 // fully monomorphic (i.e., includes type parameters),
1550 // this is because those type parameters may
1551 // ultimately be bound to types from other crates that
1552 // may have specialized impls we can't see. In the
1553 // case where the trait ref IS fully monomorphic, this
1554 // is a policy decision that we made in the RFC in
1555 // order to preserve flexibility for the crate that
1556 // defined the specializable impl to specialize later
1557 // for existing types.
1559 // In either case, we handle this by not adding a
1560 // candidate for an impl if it contains a `default`
1563 // NOTE: This should be kept in sync with the similar code in
1564 // `rustc_ty_utils::instance::resolve_associated_item()`.
1566 assoc_def(selcx, impl_data.impl_def_id, obligation.predicate.item_def_id)
1567 .map_err(|ErrorGuaranteed { .. }| ())?;
1569 if node_item.is_final() {
1570 // Non-specializable items are always projectable.
1573 // Only reveal a specializable default if we're past type-checking
1574 // and the obligation is monomorphic, otherwise passes such as
1575 // transmute checking and polymorphic MIR optimizations could
1576 // get a result which isn't correct for all monomorphizations.
1577 if obligation.param_env.reveal() == Reveal::All {
1578 // NOTE(eddyb) inference variables can resolve to parameters, so
1579 // assume `poly_trait_ref` isn't monomorphic, if it contains any.
1580 let poly_trait_ref = selcx.infcx().resolve_vars_if_possible(poly_trait_ref);
1581 !poly_trait_ref.still_further_specializable()
1584 assoc_ty = ?selcx.tcx().def_path_str(node_item.item.def_id),
1585 ?obligation.predicate,
1586 "assemble_candidates_from_impls: not eligible due to default",
1592 super::ImplSource::DiscriminantKind(..) => {
1593 // While `DiscriminantKind` is automatically implemented for every type,
1594 // the concrete discriminant may not be known yet.
1596 // Any type with multiple potential discriminant types is therefore not eligible.
1597 let self_ty = selcx.infcx().shallow_resolve(obligation.predicate.self_ty());
1599 match self_ty.kind() {
1617 | ty::GeneratorWitness(..)
1620 // Integers and floats always have `u8` as their discriminant.
1621 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(..)) => true,
1627 | ty::Placeholder(..)
1629 | ty::Error(_) => false,
1632 super::ImplSource::Pointee(..) => {
1633 // While `Pointee` is automatically implemented for every type,
1634 // the concrete metadata type may not be known yet.
1636 // Any type with multiple potential metadata types is therefore not eligible.
1637 let self_ty = selcx.infcx().shallow_resolve(obligation.predicate.self_ty());
1639 let tail = selcx.tcx().struct_tail_with_normalize(
1642 // We throw away any obligations we get from this, since we normalize
1643 // and confirm these obligations once again during confirmation
1644 normalize_with_depth(
1646 obligation.param_env,
1647 obligation.cause.clone(),
1648 obligation.recursion_depth + 1,
1672 | ty::GeneratorWitness(..)
1674 // Extern types have unit metadata, according to RFC 2850
1676 // If returned by `struct_tail_without_normalization` this is a unit struct
1677 // without any fields, or not a struct, and therefore is Sized.
1679 // If returned by `struct_tail_without_normalization` this is the empty tuple.
1681 // Integers and floats are always Sized, and so have unit type metadata.
1682 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(..)) => true,
1684 // type parameters, opaques, and unnormalized projections have pointer
1685 // metadata if they're known (e.g. by the param_env) to be sized
1686 ty::Param(_) | ty::Projection(..) | ty::Opaque(..)
1687 if selcx.infcx().predicate_must_hold_modulo_regions(
1689 ty::Binder::dummy(ty::TraitRef::new(
1690 selcx.tcx().require_lang_item(LangItem::Sized, None),
1691 selcx.tcx().mk_substs_trait(self_ty, &[]),
1694 .to_predicate(selcx.tcx()),
1701 // FIXME(compiler-errors): are Bound and Placeholder types ever known sized?
1703 | ty::Projection(..)
1706 | ty::Placeholder(..)
1709 if tail.has_infer_types() {
1710 candidate_set.mark_ambiguous();
1716 super::ImplSource::Param(..) => {
1717 // This case tell us nothing about the value of an
1718 // associated type. Consider:
1721 // trait SomeTrait { type Foo; }
1722 // fn foo<T:SomeTrait>(...) { }
1725 // If the user writes `<T as SomeTrait>::Foo`, then the `T
1726 // : SomeTrait` binding does not help us decide what the
1727 // type `Foo` is (at least, not more specifically than
1728 // what we already knew).
1730 // But wait, you say! What about an example like this:
1733 // fn bar<T:SomeTrait<Foo=usize>>(...) { ... }
1736 // Doesn't the `T : SomeTrait<Foo=usize>` predicate help
1737 // resolve `T::Foo`? And of course it does, but in fact
1738 // that single predicate is desugared into two predicates
1739 // in the compiler: a trait predicate (`T : SomeTrait`) and a
1740 // projection. And the projection where clause is handled
1741 // in `assemble_candidates_from_param_env`.
1744 super::ImplSource::Object(_) => {
1745 // Handled by the `Object` projection candidate. See
1746 // `assemble_candidates_from_object_ty` for an explanation of
1747 // why we special case object types.
1750 super::ImplSource::AutoImpl(..)
1751 | super::ImplSource::Builtin(..)
1752 | super::ImplSource::TraitUpcasting(_)
1753 | super::ImplSource::ConstDestruct(_)
1754 | super::ImplSource::Tuple => {
1755 // These traits have no associated types.
1756 selcx.tcx().sess.delay_span_bug(
1757 obligation.cause.span,
1758 &format!("Cannot project an associated type from `{:?}`", impl_source),
1765 if candidate_set.push_candidate(ProjectionCandidate::Select(impl_source)) {
1776 fn confirm_candidate<'cx, 'tcx>(
1777 selcx: &mut SelectionContext<'cx, 'tcx>,
1778 obligation: &ProjectionTyObligation<'tcx>,
1779 candidate: ProjectionCandidate<'tcx>,
1780 ) -> Progress<'tcx> {
1781 debug!(?obligation, ?candidate, "confirm_candidate");
1782 let mut progress = match candidate {
1783 ProjectionCandidate::ParamEnv(poly_projection)
1784 | ProjectionCandidate::Object(poly_projection) => {
1785 confirm_param_env_candidate(selcx, obligation, poly_projection, false)
1788 ProjectionCandidate::TraitDef(poly_projection) => {
1789 confirm_param_env_candidate(selcx, obligation, poly_projection, true)
1792 ProjectionCandidate::Select(impl_source) => {
1793 confirm_select_candidate(selcx, obligation, impl_source)
1795 ProjectionCandidate::ImplTraitInTrait(data) => {
1796 confirm_impl_trait_in_trait_candidate(selcx, obligation, data)
1800 // When checking for cycle during evaluation, we compare predicates with
1801 // "syntactic" equality. Since normalization generally introduces a type
1802 // with new region variables, we need to resolve them to existing variables
1803 // when possible for this to work. See `auto-trait-projection-recursion.rs`
1804 // for a case where this matters.
1805 if progress.term.has_infer_regions() {
1807 progress.term.fold_with(&mut OpportunisticRegionResolver::new(selcx.infcx()));
1812 fn confirm_select_candidate<'cx, 'tcx>(
1813 selcx: &mut SelectionContext<'cx, 'tcx>,
1814 obligation: &ProjectionTyObligation<'tcx>,
1815 impl_source: Selection<'tcx>,
1816 ) -> Progress<'tcx> {
1818 super::ImplSource::UserDefined(data) => confirm_impl_candidate(selcx, obligation, data),
1819 super::ImplSource::Generator(data) => confirm_generator_candidate(selcx, obligation, data),
1820 super::ImplSource::Closure(data) => confirm_closure_candidate(selcx, obligation, data),
1821 super::ImplSource::FnPointer(data) => confirm_fn_pointer_candidate(selcx, obligation, data),
1822 super::ImplSource::DiscriminantKind(data) => {
1823 confirm_discriminant_kind_candidate(selcx, obligation, data)
1825 super::ImplSource::Pointee(data) => confirm_pointee_candidate(selcx, obligation, data),
1826 super::ImplSource::Object(_)
1827 | super::ImplSource::AutoImpl(..)
1828 | super::ImplSource::Param(..)
1829 | super::ImplSource::Builtin(..)
1830 | super::ImplSource::TraitUpcasting(_)
1831 | super::ImplSource::TraitAlias(..)
1832 | super::ImplSource::ConstDestruct(_)
1833 | super::ImplSource::Tuple => {
1834 // we don't create Select candidates with this kind of resolution
1836 obligation.cause.span,
1837 "Cannot project an associated type from `{:?}`",
1844 fn confirm_generator_candidate<'cx, 'tcx>(
1845 selcx: &mut SelectionContext<'cx, 'tcx>,
1846 obligation: &ProjectionTyObligation<'tcx>,
1847 impl_source: ImplSourceGeneratorData<'tcx, PredicateObligation<'tcx>>,
1848 ) -> Progress<'tcx> {
1849 let gen_sig = impl_source.substs.as_generator().poly_sig();
1850 let Normalized { value: gen_sig, obligations } = normalize_with_depth(
1852 obligation.param_env,
1853 obligation.cause.clone(),
1854 obligation.recursion_depth + 1,
1858 debug!(?obligation, ?gen_sig, ?obligations, "confirm_generator_candidate");
1860 let tcx = selcx.tcx();
1862 let gen_def_id = tcx.require_lang_item(LangItem::Generator, None);
1864 let predicate = super::util::generator_trait_ref_and_outputs(
1867 obligation.predicate.self_ty(),
1870 .map_bound(|(trait_ref, yield_ty, return_ty)| {
1871 let name = tcx.associated_item(obligation.predicate.item_def_id).name;
1872 let ty = if name == sym::Return {
1874 } else if name == sym::Yield {
1880 ty::ProjectionPredicate {
1881 projection_ty: ty::ProjectionTy {
1882 substs: trait_ref.substs,
1883 item_def_id: obligation.predicate.item_def_id,
1889 confirm_param_env_candidate(selcx, obligation, predicate, false)
1890 .with_addl_obligations(impl_source.nested)
1891 .with_addl_obligations(obligations)
1894 fn confirm_discriminant_kind_candidate<'cx, 'tcx>(
1895 selcx: &mut SelectionContext<'cx, 'tcx>,
1896 obligation: &ProjectionTyObligation<'tcx>,
1897 _: ImplSourceDiscriminantKindData,
1898 ) -> Progress<'tcx> {
1899 let tcx = selcx.tcx();
1901 let self_ty = selcx.infcx().shallow_resolve(obligation.predicate.self_ty());
1902 // We get here from `poly_project_and_unify_type` which replaces bound vars
1903 // with placeholders
1904 debug_assert!(!self_ty.has_escaping_bound_vars());
1905 let substs = tcx.mk_substs([self_ty.into()].iter());
1907 let discriminant_def_id = tcx.require_lang_item(LangItem::Discriminant, None);
1909 let predicate = ty::ProjectionPredicate {
1910 projection_ty: ty::ProjectionTy { substs, item_def_id: discriminant_def_id },
1911 term: self_ty.discriminant_ty(tcx).into(),
1914 // We get here from `poly_project_and_unify_type` which replaces bound vars
1915 // with placeholders, so dummy is okay here.
1916 confirm_param_env_candidate(selcx, obligation, ty::Binder::dummy(predicate), false)
1919 fn confirm_pointee_candidate<'cx, 'tcx>(
1920 selcx: &mut SelectionContext<'cx, 'tcx>,
1921 obligation: &ProjectionTyObligation<'tcx>,
1922 _: ImplSourcePointeeData,
1923 ) -> Progress<'tcx> {
1924 let tcx = selcx.tcx();
1925 let self_ty = selcx.infcx().shallow_resolve(obligation.predicate.self_ty());
1927 let mut obligations = vec![];
1928 let (metadata_ty, check_is_sized) = self_ty.ptr_metadata_ty(tcx, |ty| {
1929 normalize_with_depth_to(
1931 obligation.param_env,
1932 obligation.cause.clone(),
1933 obligation.recursion_depth + 1,
1939 let sized_predicate = ty::Binder::dummy(ty::TraitRef::new(
1940 tcx.require_lang_item(LangItem::Sized, None),
1941 tcx.mk_substs_trait(self_ty, &[]),
1945 obligations.push(Obligation::new(
1946 obligation.cause.clone(),
1947 obligation.param_env,
1952 let substs = tcx.mk_substs([self_ty.into()].iter());
1953 let metadata_def_id = tcx.require_lang_item(LangItem::Metadata, None);
1955 let predicate = ty::ProjectionPredicate {
1956 projection_ty: ty::ProjectionTy { substs, item_def_id: metadata_def_id },
1957 term: metadata_ty.into(),
1960 confirm_param_env_candidate(selcx, obligation, ty::Binder::dummy(predicate), false)
1961 .with_addl_obligations(obligations)
1964 fn confirm_fn_pointer_candidate<'cx, 'tcx>(
1965 selcx: &mut SelectionContext<'cx, 'tcx>,
1966 obligation: &ProjectionTyObligation<'tcx>,
1967 fn_pointer_impl_source: ImplSourceFnPointerData<'tcx, PredicateObligation<'tcx>>,
1968 ) -> Progress<'tcx> {
1969 let fn_type = selcx.infcx().shallow_resolve(fn_pointer_impl_source.fn_ty);
1970 let sig = fn_type.fn_sig(selcx.tcx());
1971 let Normalized { value: sig, obligations } = normalize_with_depth(
1973 obligation.param_env,
1974 obligation.cause.clone(),
1975 obligation.recursion_depth + 1,
1979 confirm_callable_candidate(selcx, obligation, sig, util::TupleArgumentsFlag::Yes)
1980 .with_addl_obligations(fn_pointer_impl_source.nested)
1981 .with_addl_obligations(obligations)
1984 fn confirm_closure_candidate<'cx, 'tcx>(
1985 selcx: &mut SelectionContext<'cx, 'tcx>,
1986 obligation: &ProjectionTyObligation<'tcx>,
1987 impl_source: ImplSourceClosureData<'tcx, PredicateObligation<'tcx>>,
1988 ) -> Progress<'tcx> {
1989 let closure_sig = impl_source.substs.as_closure().sig();
1990 let Normalized { value: closure_sig, obligations } = normalize_with_depth(
1992 obligation.param_env,
1993 obligation.cause.clone(),
1994 obligation.recursion_depth + 1,
1998 debug!(?obligation, ?closure_sig, ?obligations, "confirm_closure_candidate");
2000 confirm_callable_candidate(selcx, obligation, closure_sig, util::TupleArgumentsFlag::No)
2001 .with_addl_obligations(impl_source.nested)
2002 .with_addl_obligations(obligations)
2005 fn confirm_callable_candidate<'cx, 'tcx>(
2006 selcx: &mut SelectionContext<'cx, 'tcx>,
2007 obligation: &ProjectionTyObligation<'tcx>,
2008 fn_sig: ty::PolyFnSig<'tcx>,
2009 flag: util::TupleArgumentsFlag,
2010 ) -> Progress<'tcx> {
2011 let tcx = selcx.tcx();
2013 debug!(?obligation, ?fn_sig, "confirm_callable_candidate");
2015 let fn_once_def_id = tcx.require_lang_item(LangItem::FnOnce, None);
2016 let fn_once_output_def_id = tcx.require_lang_item(LangItem::FnOnceOutput, None);
2018 let predicate = super::util::closure_trait_ref_and_return_type(
2021 obligation.predicate.self_ty(),
2025 .map_bound(|(trait_ref, ret_type)| ty::ProjectionPredicate {
2026 projection_ty: ty::ProjectionTy {
2027 substs: trait_ref.substs,
2028 item_def_id: fn_once_output_def_id,
2030 term: ret_type.into(),
2033 confirm_param_env_candidate(selcx, obligation, predicate, true)
2036 fn confirm_param_env_candidate<'cx, 'tcx>(
2037 selcx: &mut SelectionContext<'cx, 'tcx>,
2038 obligation: &ProjectionTyObligation<'tcx>,
2039 poly_cache_entry: ty::PolyProjectionPredicate<'tcx>,
2040 potentially_unnormalized_candidate: bool,
2041 ) -> Progress<'tcx> {
2042 let infcx = selcx.infcx();
2043 let cause = &obligation.cause;
2044 let param_env = obligation.param_env;
2046 let cache_entry = infcx.replace_bound_vars_with_fresh_vars(
2048 LateBoundRegionConversionTime::HigherRankedType,
2052 let cache_projection = cache_entry.projection_ty;
2053 let mut nested_obligations = Vec::new();
2054 let obligation_projection = obligation.predicate;
2055 let obligation_projection = ensure_sufficient_stack(|| {
2056 normalize_with_depth_to(
2058 obligation.param_env,
2059 obligation.cause.clone(),
2060 obligation.recursion_depth + 1,
2061 obligation_projection,
2062 &mut nested_obligations,
2065 let cache_projection = if potentially_unnormalized_candidate {
2066 ensure_sufficient_stack(|| {
2067 normalize_with_depth_to(
2069 obligation.param_env,
2070 obligation.cause.clone(),
2071 obligation.recursion_depth + 1,
2073 &mut nested_obligations,
2080 debug!(?cache_projection, ?obligation_projection);
2082 match infcx.at(cause, param_env).eq(cache_projection, obligation_projection) {
2083 Ok(InferOk { value: _, obligations }) => {
2084 nested_obligations.extend(obligations);
2085 assoc_ty_own_obligations(selcx, obligation, &mut nested_obligations);
2086 // FIXME(associated_const_equality): Handle consts here as well? Maybe this progress type should just take
2088 Progress { term: cache_entry.term, obligations: nested_obligations }
2092 "Failed to unify obligation `{:?}` with poly_projection `{:?}`: {:?}",
2093 obligation, poly_cache_entry, e,
2095 debug!("confirm_param_env_candidate: {}", msg);
2096 let err = infcx.tcx.ty_error_with_message(obligation.cause.span, &msg);
2097 Progress { term: err.into(), obligations: vec![] }
2102 fn confirm_impl_candidate<'cx, 'tcx>(
2103 selcx: &mut SelectionContext<'cx, 'tcx>,
2104 obligation: &ProjectionTyObligation<'tcx>,
2105 impl_impl_source: ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>>,
2106 ) -> Progress<'tcx> {
2107 let tcx = selcx.tcx();
2109 let ImplSourceUserDefinedData { impl_def_id, substs, mut nested } = impl_impl_source;
2110 let assoc_item_id = obligation.predicate.item_def_id;
2111 let trait_def_id = tcx.trait_id_of_impl(impl_def_id).unwrap();
2113 let param_env = obligation.param_env;
2114 let Ok(assoc_ty) = assoc_def(selcx, impl_def_id, assoc_item_id) else {
2115 return Progress { term: tcx.ty_error().into(), obligations: nested };
2118 if !assoc_ty.item.defaultness(tcx).has_value() {
2119 // This means that the impl is missing a definition for the
2120 // associated type. This error will be reported by the type
2121 // checker method `check_impl_items_against_trait`, so here we
2122 // just return Error.
2124 "confirm_impl_candidate: no associated type {:?} for {:?}",
2125 assoc_ty.item.name, obligation.predicate
2127 return Progress { term: tcx.ty_error().into(), obligations: nested };
2129 // If we're trying to normalize `<Vec<u32> as X>::A<S>` using
2130 //`impl<T> X for Vec<T> { type A<Y> = Box<Y>; }`, then:
2132 // * `obligation.predicate.substs` is `[Vec<u32>, S]`
2133 // * `substs` is `[u32]`
2134 // * `substs` ends up as `[u32, S]`
2135 let substs = obligation.predicate.substs.rebase_onto(tcx, trait_def_id, substs);
2137 translate_substs(selcx.infcx(), param_env, impl_def_id, substs, assoc_ty.defining_node);
2138 let ty = tcx.bound_type_of(assoc_ty.item.def_id);
2139 let is_const = matches!(tcx.def_kind(assoc_ty.item.def_id), DefKind::AssocConst);
2140 let term: ty::EarlyBinder<ty::Term<'tcx>> = if is_const {
2141 let identity_substs =
2142 crate::traits::InternalSubsts::identity_for_item(tcx, assoc_ty.item.def_id);
2143 let did = ty::WithOptConstParam::unknown(assoc_ty.item.def_id);
2144 let kind = ty::ConstKind::Unevaluated(ty::UnevaluatedConst::new(did, identity_substs));
2145 ty.map_bound(|ty| tcx.mk_const(ty::ConstS { ty, kind }).into())
2147 ty.map_bound(|ty| ty.into())
2149 if !check_substs_compatible(tcx, &assoc_ty.item, substs) {
2150 let err = tcx.ty_error_with_message(
2151 obligation.cause.span,
2152 "impl item and trait item have different parameters",
2154 Progress { term: err.into(), obligations: nested }
2156 assoc_ty_own_obligations(selcx, obligation, &mut nested);
2157 Progress { term: term.subst(tcx, substs), obligations: nested }
2161 // Verify that the trait item and its implementation have compatible substs lists
2162 fn check_substs_compatible<'tcx>(
2164 assoc_ty: &ty::AssocItem,
2165 substs: ty::SubstsRef<'tcx>,
2167 fn check_substs_compatible_inner<'tcx>(
2169 generics: &'tcx ty::Generics,
2170 args: &'tcx [ty::GenericArg<'tcx>],
2172 if generics.count() != args.len() {
2176 let (parent_args, own_args) = args.split_at(generics.parent_count);
2178 if let Some(parent) = generics.parent
2179 && let parent_generics = tcx.generics_of(parent)
2180 && !check_substs_compatible_inner(tcx, parent_generics, parent_args) {
2184 for (param, arg) in std::iter::zip(&generics.params, own_args) {
2185 match (¶m.kind, arg.unpack()) {
2186 (ty::GenericParamDefKind::Type { .. }, ty::GenericArgKind::Type(_))
2187 | (ty::GenericParamDefKind::Lifetime, ty::GenericArgKind::Lifetime(_))
2188 | (ty::GenericParamDefKind::Const { .. }, ty::GenericArgKind::Const(_)) => {}
2196 check_substs_compatible_inner(tcx, tcx.generics_of(assoc_ty.def_id), substs.as_slice())
2199 fn confirm_impl_trait_in_trait_candidate<'tcx>(
2200 selcx: &mut SelectionContext<'_, 'tcx>,
2201 obligation: &ProjectionTyObligation<'tcx>,
2202 data: ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>>,
2203 ) -> Progress<'tcx> {
2204 let tcx = selcx.tcx();
2205 let mut obligations = data.nested;
2207 let trait_fn_def_id = tcx.impl_trait_in_trait_parent(obligation.predicate.item_def_id);
2208 let Ok(leaf_def) = assoc_def(selcx, data.impl_def_id, trait_fn_def_id) else {
2209 return Progress { term: tcx.ty_error().into(), obligations };
2211 if !leaf_def.item.defaultness(tcx).has_value() {
2212 return Progress { term: tcx.ty_error().into(), obligations };
2215 let impl_fn_def_id = leaf_def.item.def_id;
2216 let impl_fn_substs = obligation.predicate.substs.rebase_onto(tcx, trait_fn_def_id, data.substs);
2218 let cause = ObligationCause::new(
2219 obligation.cause.span,
2220 obligation.cause.body_id,
2221 super::ItemObligation(impl_fn_def_id),
2223 let predicates = normalize_with_depth_to(
2225 obligation.param_env,
2227 obligation.recursion_depth + 1,
2228 tcx.predicates_of(impl_fn_def_id).instantiate(tcx, impl_fn_substs),
2231 obligations.extend(std::iter::zip(predicates.predicates, predicates.spans).map(
2233 Obligation::with_depth(
2234 ObligationCause::new(
2235 obligation.cause.span,
2236 obligation.cause.body_id,
2237 if span.is_dummy() {
2238 super::ItemObligation(impl_fn_def_id)
2240 super::BindingObligation(impl_fn_def_id, span)
2243 obligation.recursion_depth + 1,
2244 obligation.param_env,
2250 let ty = super::normalize_to(
2252 obligation.param_env,
2254 tcx.bound_trait_impl_trait_tys(impl_fn_def_id)
2256 tys.map_or_else(|_| tcx.ty_error(), |tys| tys[&obligation.predicate.item_def_id])
2258 .subst(tcx, impl_fn_substs),
2262 Progress { term: ty.into(), obligations }
2265 // Get obligations corresponding to the predicates from the where-clause of the
2266 // associated type itself.
2267 fn assoc_ty_own_obligations<'cx, 'tcx>(
2268 selcx: &mut SelectionContext<'cx, 'tcx>,
2269 obligation: &ProjectionTyObligation<'tcx>,
2270 nested: &mut Vec<PredicateObligation<'tcx>>,
2272 let tcx = selcx.tcx();
2273 for predicate in tcx
2274 .predicates_of(obligation.predicate.item_def_id)
2275 .instantiate_own(tcx, obligation.predicate.substs)
2278 let normalized = normalize_with_depth_to(
2280 obligation.param_env,
2281 obligation.cause.clone(),
2282 obligation.recursion_depth + 1,
2286 nested.push(Obligation::with_depth(
2287 obligation.cause.clone(),
2288 obligation.recursion_depth + 1,
2289 obligation.param_env,
2295 /// Locate the definition of an associated type in the specialization hierarchy,
2296 /// starting from the given impl.
2298 /// Based on the "projection mode", this lookup may in fact only examine the
2299 /// topmost impl. See the comments for `Reveal` for more details.
2301 selcx: &SelectionContext<'_, '_>,
2303 assoc_def_id: DefId,
2304 ) -> Result<specialization_graph::LeafDef, ErrorGuaranteed> {
2305 let tcx = selcx.tcx();
2306 let trait_def_id = tcx.impl_trait_ref(impl_def_id).unwrap().def_id;
2307 let trait_def = tcx.trait_def(trait_def_id);
2309 // This function may be called while we are still building the
2310 // specialization graph that is queried below (via TraitDef::ancestors()),
2311 // so, in order to avoid unnecessary infinite recursion, we manually look
2312 // for the associated item at the given impl.
2313 // If there is no such item in that impl, this function will fail with a
2314 // cycle error if the specialization graph is currently being built.
2315 if let Some(&impl_item_id) = tcx.impl_item_implementor_ids(impl_def_id).get(&assoc_def_id) {
2316 let item = tcx.associated_item(impl_item_id);
2317 let impl_node = specialization_graph::Node::Impl(impl_def_id);
2318 return Ok(specialization_graph::LeafDef {
2320 defining_node: impl_node,
2321 finalizing_node: if item.defaultness(tcx).is_default() {
2329 let ancestors = trait_def.ancestors(tcx, impl_def_id)?;
2330 if let Some(assoc_item) = ancestors.leaf_def(tcx, assoc_def_id) {
2333 // This is saying that neither the trait nor
2334 // the impl contain a definition for this
2335 // associated type. Normally this situation
2336 // could only arise through a compiler bug --
2337 // if the user wrote a bad item name, it
2338 // should have failed in astconv.
2340 "No associated type `{}` for {}",
2341 tcx.item_name(assoc_def_id),
2342 tcx.def_path_str(impl_def_id)
2347 pub(crate) trait ProjectionCacheKeyExt<'cx, 'tcx>: Sized {
2348 fn from_poly_projection_predicate(
2349 selcx: &mut SelectionContext<'cx, 'tcx>,
2350 predicate: ty::PolyProjectionPredicate<'tcx>,
2354 impl<'cx, 'tcx> ProjectionCacheKeyExt<'cx, 'tcx> for ProjectionCacheKey<'tcx> {
2355 fn from_poly_projection_predicate(
2356 selcx: &mut SelectionContext<'cx, 'tcx>,
2357 predicate: ty::PolyProjectionPredicate<'tcx>,
2359 let infcx = selcx.infcx();
2360 // We don't do cross-snapshot caching of obligations with escaping regions,
2361 // so there's no cache key to use
2362 predicate.no_bound_vars().map(|predicate| {
2363 ProjectionCacheKey::new(
2364 // We don't attempt to match up with a specific type-variable state
2365 // from a specific call to `opt_normalize_projection_type` - if
2366 // there's no precise match, the original cache entry is "stranded"
2368 infcx.resolve_vars_if_possible(predicate.projection_ty),