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
66 /// `<<A as Trait>::B as Trait2>::C`.
67 TraitDef(ty::PolyProjectionPredicate<'tcx>),
69 /// Bounds specified on an object type
70 Object(ty::PolyProjectionPredicate<'tcx>),
72 /// From an "impl" (or a "pseudo-impl" returned by select)
73 Select(Selection<'tcx>),
75 ImplTraitInTrait(ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>>),
78 enum ProjectionCandidateSet<'tcx> {
80 Single(ProjectionCandidate<'tcx>),
82 Error(SelectionError<'tcx>),
85 impl<'tcx> ProjectionCandidateSet<'tcx> {
86 fn mark_ambiguous(&mut self) {
87 *self = ProjectionCandidateSet::Ambiguous;
90 fn mark_error(&mut self, err: SelectionError<'tcx>) {
91 *self = ProjectionCandidateSet::Error(err);
94 // Returns true if the push was successful, or false if the candidate
95 // was discarded -- this could be because of ambiguity, or because
96 // a higher-priority candidate is already there.
97 fn push_candidate(&mut self, candidate: ProjectionCandidate<'tcx>) -> bool {
98 use self::ProjectionCandidate::*;
99 use self::ProjectionCandidateSet::*;
101 // This wacky variable is just used to try and
102 // make code readable and avoid confusing paths.
103 // It is assigned a "value" of `()` only on those
104 // paths in which we wish to convert `*self` to
105 // ambiguous (and return false, because the candidate
106 // was not used). On other paths, it is not assigned,
107 // and hence if those paths *could* reach the code that
108 // comes after the match, this fn would not compile.
109 let convert_to_ambiguous;
113 *self = Single(candidate);
118 // Duplicates can happen inside ParamEnv. In the case, we
119 // perform a lazy deduplication.
120 if current == &candidate {
124 // Prefer where-clauses. As in select, if there are multiple
125 // candidates, we prefer where-clause candidates over impls. This
126 // may seem a bit surprising, since impls are the source of
127 // "truth" in some sense, but in fact some of the impls that SEEM
128 // applicable are not, because of nested obligations. Where
129 // clauses are the safer choice. See the comment on
130 // `select::SelectionCandidate` and #21974 for more details.
131 match (current, candidate) {
132 (ParamEnv(..), ParamEnv(..)) => convert_to_ambiguous = (),
133 (ParamEnv(..), _) => return false,
134 (_, ParamEnv(..)) => unreachable!(),
135 (_, _) => convert_to_ambiguous = (),
139 Ambiguous | Error(..) => {
144 // We only ever get here when we moved from a single candidate
146 let () = convert_to_ambiguous;
152 /// States returned from `poly_project_and_unify_type`. Takes the place
153 /// of the old return type, which was:
154 /// ```ignore (not-rust)
156 /// Result<Option<Vec<PredicateObligation<'tcx>>>, InProgress>,
157 /// MismatchedProjectionTypes<'tcx>,
160 pub(super) enum ProjectAndUnifyResult<'tcx> {
161 /// The projection bound holds subject to the given obligations. If the
162 /// projection cannot be normalized because the required trait bound does
163 /// not hold, this is returned, with `obligations` being a predicate that
164 /// cannot be proven.
165 Holds(Vec<PredicateObligation<'tcx>>),
166 /// The projection cannot be normalized due to ambiguity. Resolving some
167 /// inference variables in the projection may fix this.
169 /// The project cannot be normalized because `poly_project_and_unify_type`
170 /// is called recursively while normalizing the same projection.
172 // the projection can be normalized, but is not equal to the expected type.
173 // Returns the type error that arose from the mismatch.
174 MismatchedProjectionTypes(MismatchedProjectionTypes<'tcx>),
177 /// Evaluates constraints of the form:
178 /// ```ignore (not-rust)
179 /// for<...> <T as Trait>::U == V
181 /// If successful, this may result in additional obligations. Also returns
182 /// the projection cache key used to track these additional obligations.
183 #[instrument(level = "debug", skip(selcx))]
184 pub(super) fn poly_project_and_unify_type<'cx, 'tcx>(
185 selcx: &mut SelectionContext<'cx, 'tcx>,
186 obligation: &PolyProjectionObligation<'tcx>,
187 ) -> ProjectAndUnifyResult<'tcx> {
188 let infcx = selcx.infcx();
189 let r = infcx.commit_if_ok(|_snapshot| {
190 let old_universe = infcx.universe();
191 let placeholder_predicate =
192 infcx.replace_bound_vars_with_placeholders(obligation.predicate);
193 let new_universe = infcx.universe();
195 let placeholder_obligation = obligation.with(placeholder_predicate);
196 match project_and_unify_type(selcx, &placeholder_obligation) {
197 ProjectAndUnifyResult::MismatchedProjectionTypes(e) => Err(e),
198 ProjectAndUnifyResult::Holds(obligations)
199 if old_universe != new_universe
200 && selcx.tcx().features().generic_associated_types_extended =>
202 // If the `generic_associated_types_extended` feature is active, then we ignore any
203 // obligations references lifetimes from any universe greater than or equal to the
204 // universe just created. Otherwise, we can end up with something like `for<'a> I: 'a`,
205 // which isn't quite what we want. Ideally, we want either an implied
206 // `for<'a where I: 'a> I: 'a` or we want to "lazily" check these hold when we
207 // substitute concrete regions. There is design work to be done here; until then,
208 // however, this allows experimenting potential GAT features without running into
209 // well-formedness issues.
210 let new_obligations = obligations
212 .filter(|obligation| {
213 let mut visitor = MaxUniverse::new();
214 obligation.predicate.visit_with(&mut visitor);
215 visitor.max_universe() < new_universe
218 Ok(ProjectAndUnifyResult::Holds(new_obligations))
226 Err(err) => ProjectAndUnifyResult::MismatchedProjectionTypes(err),
230 /// Evaluates constraints of the form:
231 /// ```ignore (not-rust)
232 /// <T as Trait>::U == V
234 /// If successful, this may result in additional obligations.
236 /// See [poly_project_and_unify_type] for an explanation of the return value.
237 #[instrument(level = "debug", skip(selcx))]
238 fn project_and_unify_type<'cx, 'tcx>(
239 selcx: &mut SelectionContext<'cx, 'tcx>,
240 obligation: &ProjectionObligation<'tcx>,
241 ) -> ProjectAndUnifyResult<'tcx> {
242 let mut obligations = vec![];
244 let infcx = selcx.infcx();
245 let normalized = match opt_normalize_projection_type(
247 obligation.param_env,
248 obligation.predicate.projection_ty,
249 obligation.cause.clone(),
250 obligation.recursion_depth,
254 Ok(None) => return ProjectAndUnifyResult::FailedNormalization,
255 Err(InProgress) => return ProjectAndUnifyResult::Recursive,
257 debug!(?normalized, ?obligations, "project_and_unify_type result");
258 let actual = obligation.predicate.term;
259 // For an example where this is neccessary see src/test/ui/impl-trait/nested-return-type2.rs
260 // This allows users to omit re-mentioning all bounds on an associated type and just use an
261 // `impl Trait` for the assoc type to add more bounds.
262 let InferOk { value: actual, obligations: new } =
263 selcx.infcx().replace_opaque_types_with_inference_vars(
265 obligation.cause.body_id,
266 obligation.cause.span,
267 obligation.param_env,
269 obligations.extend(new);
271 match infcx.at(&obligation.cause, obligation.param_env).eq(normalized, actual) {
272 Ok(InferOk { obligations: inferred_obligations, value: () }) => {
273 obligations.extend(inferred_obligations);
274 ProjectAndUnifyResult::Holds(obligations)
277 debug!("equating types encountered error {:?}", err);
278 ProjectAndUnifyResult::MismatchedProjectionTypes(MismatchedProjectionTypes { err })
283 /// Normalizes any associated type projections in `value`, replacing
284 /// them with a fully resolved type where possible. The return value
285 /// combines the normalized result and any additional obligations that
286 /// were incurred as result.
287 pub fn normalize<'a, 'b, 'tcx, T>(
288 selcx: &'a mut SelectionContext<'b, 'tcx>,
289 param_env: ty::ParamEnv<'tcx>,
290 cause: ObligationCause<'tcx>,
292 ) -> Normalized<'tcx, T>
294 T: TypeFoldable<'tcx>,
296 let mut obligations = Vec::new();
297 let value = normalize_to(selcx, param_env, cause, value, &mut obligations);
298 Normalized { value, obligations }
301 pub fn normalize_to<'a, 'b, 'tcx, T>(
302 selcx: &'a mut SelectionContext<'b, 'tcx>,
303 param_env: ty::ParamEnv<'tcx>,
304 cause: ObligationCause<'tcx>,
306 obligations: &mut Vec<PredicateObligation<'tcx>>,
309 T: TypeFoldable<'tcx>,
311 normalize_with_depth_to(selcx, param_env, cause, 0, value, obligations)
314 /// As `normalize`, but with a custom depth.
315 pub fn normalize_with_depth<'a, 'b, 'tcx, T>(
316 selcx: &'a mut SelectionContext<'b, 'tcx>,
317 param_env: ty::ParamEnv<'tcx>,
318 cause: ObligationCause<'tcx>,
321 ) -> Normalized<'tcx, T>
323 T: TypeFoldable<'tcx>,
325 let mut obligations = Vec::new();
326 let value = normalize_with_depth_to(selcx, param_env, cause, depth, value, &mut obligations);
327 Normalized { value, obligations }
330 #[instrument(level = "info", skip(selcx, param_env, cause, obligations))]
331 pub fn normalize_with_depth_to<'a, 'b, 'tcx, T>(
332 selcx: &'a mut SelectionContext<'b, 'tcx>,
333 param_env: ty::ParamEnv<'tcx>,
334 cause: ObligationCause<'tcx>,
337 obligations: &mut Vec<PredicateObligation<'tcx>>,
340 T: TypeFoldable<'tcx>,
342 debug!(obligations.len = obligations.len());
343 let mut normalizer = AssocTypeNormalizer::new(selcx, param_env, cause, depth, obligations);
344 let result = ensure_sufficient_stack(|| normalizer.fold(value));
345 debug!(?result, obligations.len = normalizer.obligations.len());
346 debug!(?normalizer.obligations,);
350 #[instrument(level = "info", skip(selcx, param_env, cause, obligations))]
351 pub fn try_normalize_with_depth_to<'a, 'b, 'tcx, T>(
352 selcx: &'a mut SelectionContext<'b, 'tcx>,
353 param_env: ty::ParamEnv<'tcx>,
354 cause: ObligationCause<'tcx>,
357 obligations: &mut Vec<PredicateObligation<'tcx>>,
360 T: TypeFoldable<'tcx>,
362 debug!(obligations.len = obligations.len());
363 let mut normalizer = AssocTypeNormalizer::new_without_eager_inference_replacement(
370 let result = ensure_sufficient_stack(|| normalizer.fold(value));
371 debug!(?result, obligations.len = normalizer.obligations.len());
372 debug!(?normalizer.obligations,);
376 pub(crate) fn needs_normalization<'tcx, T: TypeVisitable<'tcx>>(value: &T, reveal: Reveal) -> bool {
378 Reveal::UserFacing => value
379 .has_type_flags(ty::TypeFlags::HAS_TY_PROJECTION | ty::TypeFlags::HAS_CT_PROJECTION),
380 Reveal::All => value.has_type_flags(
381 ty::TypeFlags::HAS_TY_PROJECTION
382 | ty::TypeFlags::HAS_TY_OPAQUE
383 | ty::TypeFlags::HAS_CT_PROJECTION,
388 struct AssocTypeNormalizer<'a, 'b, 'tcx> {
389 selcx: &'a mut SelectionContext<'b, 'tcx>,
390 param_env: ty::ParamEnv<'tcx>,
391 cause: ObligationCause<'tcx>,
392 obligations: &'a mut Vec<PredicateObligation<'tcx>>,
394 universes: Vec<Option<ty::UniverseIndex>>,
395 /// If true, when a projection is unable to be completed, an inference
396 /// variable will be created and an obligation registered to project to that
397 /// inference variable. Also, constants will be eagerly evaluated.
398 eager_inference_replacement: bool,
401 impl<'a, 'b, 'tcx> AssocTypeNormalizer<'a, 'b, 'tcx> {
403 selcx: &'a mut SelectionContext<'b, 'tcx>,
404 param_env: ty::ParamEnv<'tcx>,
405 cause: ObligationCause<'tcx>,
407 obligations: &'a mut Vec<PredicateObligation<'tcx>>,
408 ) -> AssocTypeNormalizer<'a, 'b, 'tcx> {
409 AssocTypeNormalizer {
416 eager_inference_replacement: true,
420 fn new_without_eager_inference_replacement(
421 selcx: &'a mut SelectionContext<'b, 'tcx>,
422 param_env: ty::ParamEnv<'tcx>,
423 cause: ObligationCause<'tcx>,
425 obligations: &'a mut Vec<PredicateObligation<'tcx>>,
426 ) -> AssocTypeNormalizer<'a, 'b, 'tcx> {
427 AssocTypeNormalizer {
434 eager_inference_replacement: false,
438 fn fold<T: TypeFoldable<'tcx>>(&mut self, value: T) -> T {
439 let value = self.selcx.infcx().resolve_vars_if_possible(value);
443 !value.has_escaping_bound_vars(),
444 "Normalizing {:?} without wrapping in a `Binder`",
448 if !needs_normalization(&value, self.param_env.reveal()) {
451 value.fold_with(self)
456 impl<'a, 'b, 'tcx> TypeFolder<'tcx> for AssocTypeNormalizer<'a, 'b, 'tcx> {
457 fn tcx<'c>(&'c self) -> TyCtxt<'tcx> {
461 fn fold_binder<T: TypeFoldable<'tcx>>(
463 t: ty::Binder<'tcx, T>,
464 ) -> ty::Binder<'tcx, T> {
465 self.universes.push(None);
466 let t = t.super_fold_with(self);
467 self.universes.pop();
471 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
472 if !needs_normalization(&ty, self.param_env.reveal()) {
476 // We try to be a little clever here as a performance optimization in
477 // cases where there are nested projections under binders.
480 // for<'a> fn(<T as Foo>::One<'a, Box<dyn Bar<'a, Item=<T as Foo>::Two<'a>>>>)
482 // We normalize the substs on the projection before the projecting, but
483 // if we're naive, we'll
484 // replace bound vars on inner, project inner, replace placeholders on inner,
485 // replace bound vars on outer, project outer, replace placeholders on outer
487 // However, if we're a bit more clever, we can replace the bound vars
488 // on the entire type before normalizing nested projections, meaning we
489 // replace bound vars on outer, project inner,
490 // project outer, replace placeholders on outer
492 // This is possible because the inner `'a` will already be a placeholder
493 // when we need to normalize the inner projection
495 // On the other hand, this does add a bit of complexity, since we only
496 // replace bound vars if the current type is a `Projection` and we need
497 // to make sure we don't forget to fold the substs regardless.
500 // This is really important. While we *can* handle this, this has
501 // severe performance implications for large opaque types with
502 // late-bound regions. See `issue-88862` benchmark.
503 ty::Opaque(def_id, substs) => {
504 // Only normalize `impl Trait` outside of type inference, usually in codegen.
505 match self.param_env.reveal() {
506 Reveal::UserFacing => ty.super_fold_with(self),
509 let recursion_limit = self.tcx().recursion_limit();
510 if !recursion_limit.value_within_limit(self.depth) {
511 let obligation = Obligation::with_depth(
517 self.selcx.infcx().err_ctxt().report_overflow_error(&obligation, true);
520 let substs = substs.fold_with(self);
521 let generic_ty = self.tcx().bound_type_of(def_id);
522 let concrete_ty = generic_ty.subst(self.tcx(), substs);
524 let folded_ty = self.fold_ty(concrete_ty);
531 ty::Projection(data) if !data.has_escaping_bound_vars() => {
532 // This branch is *mostly* just an optimization: when we don't
533 // have escaping bound vars, we don't need to replace them with
534 // placeholders (see branch below). *Also*, we know that we can
535 // register an obligation to *later* project, since we know
536 // there won't be bound vars there.
537 let data = data.fold_with(self);
538 let normalized_ty = if self.eager_inference_replacement {
539 normalize_projection_type(
545 &mut self.obligations,
548 opt_normalize_projection_type(
554 &mut self.obligations,
558 .unwrap_or_else(|| ty.super_fold_with(self).into())
560 // For cases like #95134 we would like to catch overflows early
561 // otherwise they slip away away and cause ICE.
562 let recursion_limit = self.tcx().recursion_limit();
563 if !recursion_limit.value_within_limit(self.depth)
564 // HACK: Don't overflow when running cargo doc see #100991
565 && !self.tcx().sess.opts.actually_rustdoc
567 let obligation = Obligation::with_depth(
573 self.selcx.infcx().err_ctxt().report_overflow_error(&obligation, true);
579 obligations.len = ?self.obligations.len(),
580 "AssocTypeNormalizer: normalized type"
582 normalized_ty.ty().unwrap()
585 ty::Projection(data) => {
586 // If there are escaping bound vars, we temporarily replace the
587 // bound vars with placeholders. Note though, that in the case
588 // that we still can't project for whatever reason (e.g. self
589 // type isn't known enough), we *can't* register an obligation
590 // and return an inference variable (since then that obligation
591 // would have bound vars and that's a can of worms). Instead,
592 // we just give up and fall back to pretending like we never tried!
594 // Note: this isn't necessarily the final approach here; we may
595 // want to figure out how to register obligations with escaping vars
596 // or handle this some other way.
598 let infcx = self.selcx.infcx();
599 let (data, mapped_regions, mapped_types, mapped_consts) =
600 BoundVarReplacer::replace_bound_vars(infcx, &mut self.universes, data);
601 let data = data.fold_with(self);
602 let normalized_ty = opt_normalize_projection_type(
608 &mut self.obligations,
612 .map(|term| term.ty().unwrap())
613 .map(|normalized_ty| {
614 PlaceholderReplacer::replace_placeholders(
623 .unwrap_or_else(|| ty.super_fold_with(self));
629 obligations.len = ?self.obligations.len(),
630 "AssocTypeNormalizer: normalized type"
635 _ => ty.super_fold_with(self),
639 #[instrument(skip(self), level = "debug")]
640 fn fold_const(&mut self, constant: ty::Const<'tcx>) -> ty::Const<'tcx> {
641 let tcx = self.selcx.tcx();
642 if tcx.lazy_normalization() {
645 let constant = constant.super_fold_with(self);
646 debug!(?constant, ?self.param_env);
647 with_replaced_escaping_bound_vars(
651 |constant| constant.eval(tcx, self.param_env),
657 fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
658 if p.allow_normalization() && needs_normalization(&p, self.param_env.reveal()) {
659 p.super_fold_with(self)
666 pub struct BoundVarReplacer<'me, 'tcx> {
667 infcx: &'me InferCtxt<'tcx>,
668 // These three maps track the bound variable that were replaced by placeholders. It might be
669 // nice to remove these since we already have the `kind` in the placeholder; we really just need
670 // the `var` (but we *could* bring that into scope if we were to track them as we pass them).
671 mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
672 mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy>,
673 mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
674 // The current depth relative to *this* folding, *not* the entire normalization. In other words,
675 // the depth of binders we've passed here.
676 current_index: ty::DebruijnIndex,
677 // The `UniverseIndex` of the binding levels above us. These are optional, since we are lazy:
678 // we don't actually create a universe until we see a bound var we have to replace.
679 universe_indices: &'me mut Vec<Option<ty::UniverseIndex>>,
682 /// Executes `f` on `value` after replacing all escaping bound variables with placeholders
683 /// and then replaces these placeholders with the original bound variables in the result.
685 /// In most places, bound variables should be replaced right when entering a binder, making
686 /// this function unnecessary. However, normalization currently does not do that, so we have
687 /// to do this lazily.
689 /// You should not add any additional uses of this function, at least not without first
690 /// discussing it with t-types.
692 /// FIXME(@lcnr): We may even consider experimenting with eagerly replacing bound vars during
693 /// normalization as well, at which point this function will be unnecessary and can be removed.
694 pub fn with_replaced_escaping_bound_vars<'a, 'tcx, T: TypeFoldable<'tcx>, R: TypeFoldable<'tcx>>(
695 infcx: &'a InferCtxt<'tcx>,
696 universe_indices: &'a mut Vec<Option<ty::UniverseIndex>>,
698 f: impl FnOnce(T) -> R,
700 if value.has_escaping_bound_vars() {
701 let (value, mapped_regions, mapped_types, mapped_consts) =
702 BoundVarReplacer::replace_bound_vars(infcx, universe_indices, value);
703 let result = f(value);
704 PlaceholderReplacer::replace_placeholders(
717 impl<'me, 'tcx> BoundVarReplacer<'me, 'tcx> {
718 /// Returns `Some` if we *were* able to replace bound vars. If there are any bound vars that
719 /// use a binding level above `universe_indices.len()`, we fail.
720 pub fn replace_bound_vars<T: TypeFoldable<'tcx>>(
721 infcx: &'me InferCtxt<'tcx>,
722 universe_indices: &'me mut Vec<Option<ty::UniverseIndex>>,
726 BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
727 BTreeMap<ty::PlaceholderType, ty::BoundTy>,
728 BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
730 let mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion> = BTreeMap::new();
731 let mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy> = BTreeMap::new();
732 let mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar> = BTreeMap::new();
734 let mut replacer = BoundVarReplacer {
739 current_index: ty::INNERMOST,
743 let value = value.fold_with(&mut replacer);
745 (value, replacer.mapped_regions, replacer.mapped_types, replacer.mapped_consts)
748 fn universe_for(&mut self, debruijn: ty::DebruijnIndex) -> ty::UniverseIndex {
749 let infcx = self.infcx;
751 self.universe_indices.len() + self.current_index.as_usize() - debruijn.as_usize() - 1;
752 let universe = self.universe_indices[index].unwrap_or_else(|| {
753 for i in self.universe_indices.iter_mut().take(index + 1) {
754 *i = i.or_else(|| Some(infcx.create_next_universe()))
756 self.universe_indices[index].unwrap()
762 impl<'tcx> TypeFolder<'tcx> for BoundVarReplacer<'_, 'tcx> {
763 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
767 fn fold_binder<T: TypeFoldable<'tcx>>(
769 t: ty::Binder<'tcx, T>,
770 ) -> ty::Binder<'tcx, T> {
771 self.current_index.shift_in(1);
772 let t = t.super_fold_with(self);
773 self.current_index.shift_out(1);
777 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
779 ty::ReLateBound(debruijn, _)
780 if debruijn.as_usize() + 1
781 > self.current_index.as_usize() + self.universe_indices.len() =>
783 bug!("Bound vars outside of `self.universe_indices`");
785 ty::ReLateBound(debruijn, br) if debruijn >= self.current_index => {
786 let universe = self.universe_for(debruijn);
787 let p = ty::PlaceholderRegion { universe, name: br.kind };
788 self.mapped_regions.insert(p, br);
789 self.infcx.tcx.mk_region(ty::RePlaceholder(p))
795 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
797 ty::Bound(debruijn, _)
798 if debruijn.as_usize() + 1
799 > self.current_index.as_usize() + self.universe_indices.len() =>
801 bug!("Bound vars outside of `self.universe_indices`");
803 ty::Bound(debruijn, bound_ty) if debruijn >= self.current_index => {
804 let universe = self.universe_for(debruijn);
805 let p = ty::PlaceholderType { universe, name: bound_ty.var };
806 self.mapped_types.insert(p, bound_ty);
807 self.infcx.tcx.mk_ty(ty::Placeholder(p))
809 _ if t.has_vars_bound_at_or_above(self.current_index) => t.super_fold_with(self),
814 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
816 ty::ConstKind::Bound(debruijn, _)
817 if debruijn.as_usize() + 1
818 > self.current_index.as_usize() + self.universe_indices.len() =>
820 bug!("Bound vars outside of `self.universe_indices`");
822 ty::ConstKind::Bound(debruijn, bound_const) if debruijn >= self.current_index => {
823 let universe = self.universe_for(debruijn);
824 let p = ty::PlaceholderConst { universe, name: bound_const };
825 self.mapped_consts.insert(p, bound_const);
828 .mk_const(ty::ConstS { kind: ty::ConstKind::Placeholder(p), ty: ct.ty() })
830 _ => ct.super_fold_with(self),
834 fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
835 if p.has_vars_bound_at_or_above(self.current_index) { p.super_fold_with(self) } else { p }
839 // The inverse of `BoundVarReplacer`: replaces placeholders with the bound vars from which they came.
840 pub struct PlaceholderReplacer<'me, 'tcx> {
841 infcx: &'me InferCtxt<'tcx>,
842 mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
843 mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy>,
844 mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
845 universe_indices: &'me [Option<ty::UniverseIndex>],
846 current_index: ty::DebruijnIndex,
849 impl<'me, 'tcx> PlaceholderReplacer<'me, 'tcx> {
850 pub fn replace_placeholders<T: TypeFoldable<'tcx>>(
851 infcx: &'me InferCtxt<'tcx>,
852 mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
853 mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy>,
854 mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
855 universe_indices: &'me [Option<ty::UniverseIndex>],
858 let mut replacer = PlaceholderReplacer {
864 current_index: ty::INNERMOST,
866 value.fold_with(&mut replacer)
870 impl<'tcx> TypeFolder<'tcx> for PlaceholderReplacer<'_, 'tcx> {
871 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
875 fn fold_binder<T: TypeFoldable<'tcx>>(
877 t: ty::Binder<'tcx, T>,
878 ) -> ty::Binder<'tcx, T> {
879 if !t.has_placeholders() && !t.has_infer_regions() {
882 self.current_index.shift_in(1);
883 let t = t.super_fold_with(self);
884 self.current_index.shift_out(1);
888 fn fold_region(&mut self, r0: ty::Region<'tcx>) -> ty::Region<'tcx> {
894 .unwrap_region_constraints()
895 .opportunistic_resolve_region(self.infcx.tcx, r0),
900 ty::RePlaceholder(p) => {
901 let replace_var = self.mapped_regions.get(&p);
903 Some(replace_var) => {
907 .position(|u| matches!(u, Some(pu) if *pu == p.universe))
908 .unwrap_or_else(|| bug!("Unexpected placeholder universe."));
909 let db = ty::DebruijnIndex::from_usize(
910 self.universe_indices.len() - index + self.current_index.as_usize() - 1,
912 self.tcx().mk_region(ty::ReLateBound(db, *replace_var))
920 debug!(?r0, ?r1, ?r2, "fold_region");
925 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
927 ty::Placeholder(p) => {
928 let replace_var = self.mapped_types.get(&p);
930 Some(replace_var) => {
934 .position(|u| matches!(u, Some(pu) if *pu == p.universe))
935 .unwrap_or_else(|| bug!("Unexpected placeholder universe."));
936 let db = ty::DebruijnIndex::from_usize(
937 self.universe_indices.len() - index + self.current_index.as_usize() - 1,
939 self.tcx().mk_ty(ty::Bound(db, *replace_var))
945 _ if ty.has_placeholders() || ty.has_infer_regions() => ty.super_fold_with(self),
950 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
951 if let ty::ConstKind::Placeholder(p) = ct.kind() {
952 let replace_var = self.mapped_consts.get(&p);
954 Some(replace_var) => {
958 .position(|u| matches!(u, Some(pu) if *pu == p.universe))
959 .unwrap_or_else(|| bug!("Unexpected placeholder universe."));
960 let db = ty::DebruijnIndex::from_usize(
961 self.universe_indices.len() - index + self.current_index.as_usize() - 1,
963 self.tcx().mk_const(ty::ConstS {
964 kind: ty::ConstKind::Bound(db, *replace_var),
971 ct.super_fold_with(self)
976 /// The guts of `normalize`: normalize a specific projection like `<T
977 /// as Trait>::Item`. The result is always a type (and possibly
978 /// additional obligations). If ambiguity arises, which implies that
979 /// there are unresolved type variables in the projection, we will
980 /// substitute a fresh type variable `$X` and generate a new
981 /// obligation `<T as Trait>::Item == $X` for later.
982 pub fn normalize_projection_type<'a, 'b, 'tcx>(
983 selcx: &'a mut SelectionContext<'b, 'tcx>,
984 param_env: ty::ParamEnv<'tcx>,
985 projection_ty: ty::ProjectionTy<'tcx>,
986 cause: ObligationCause<'tcx>,
988 obligations: &mut Vec<PredicateObligation<'tcx>>,
990 opt_normalize_projection_type(
1000 .unwrap_or_else(move || {
1001 // if we bottom out in ambiguity, create a type variable
1002 // and a deferred predicate to resolve this when more type
1003 // information is available.
1007 .infer_projection(param_env, projection_ty, cause, depth + 1, obligations)
1012 /// The guts of `normalize`: normalize a specific projection like `<T
1013 /// as Trait>::Item`. The result is always a type (and possibly
1014 /// additional obligations). Returns `None` in the case of ambiguity,
1015 /// which indicates that there are unbound type variables.
1017 /// This function used to return `Option<NormalizedTy<'tcx>>`, which contains a
1018 /// `Ty<'tcx>` and an obligations vector. But that obligation vector was very
1019 /// often immediately appended to another obligations vector. So now this
1020 /// function takes an obligations vector and appends to it directly, which is
1021 /// slightly uglier but avoids the need for an extra short-lived allocation.
1022 #[instrument(level = "debug", skip(selcx, param_env, cause, obligations))]
1023 fn opt_normalize_projection_type<'a, 'b, 'tcx>(
1024 selcx: &'a mut SelectionContext<'b, 'tcx>,
1025 param_env: ty::ParamEnv<'tcx>,
1026 projection_ty: ty::ProjectionTy<'tcx>,
1027 cause: ObligationCause<'tcx>,
1029 obligations: &mut Vec<PredicateObligation<'tcx>>,
1030 ) -> Result<Option<Term<'tcx>>, InProgress> {
1031 let infcx = selcx.infcx();
1032 // Don't use the projection cache in intercrate mode -
1033 // the `infcx` may be re-used between intercrate in non-intercrate
1034 // mode, which could lead to using incorrect cache results.
1035 let use_cache = !selcx.is_intercrate();
1037 let projection_ty = infcx.resolve_vars_if_possible(projection_ty);
1038 let cache_key = ProjectionCacheKey::new(projection_ty);
1040 // FIXME(#20304) For now, I am caching here, which is good, but it
1041 // means we don't capture the type variables that are created in
1042 // the case of ambiguity. Which means we may create a large stream
1043 // of such variables. OTOH, if we move the caching up a level, we
1044 // would not benefit from caching when proving `T: Trait<U=Foo>`
1045 // bounds. It might be the case that we want two distinct caches,
1046 // or else another kind of cache entry.
1048 let cache_result = if use_cache {
1049 infcx.inner.borrow_mut().projection_cache().try_start(cache_key)
1053 match cache_result {
1054 Ok(()) => debug!("no cache"),
1055 Err(ProjectionCacheEntry::Ambiguous) => {
1056 // If we found ambiguity the last time, that means we will continue
1057 // to do so until some type in the key changes (and we know it
1058 // hasn't, because we just fully resolved it).
1059 debug!("found cache entry: ambiguous");
1062 Err(ProjectionCacheEntry::InProgress) => {
1063 // Under lazy normalization, this can arise when
1064 // bootstrapping. That is, imagine an environment with a
1065 // where-clause like `A::B == u32`. Now, if we are asked
1066 // to normalize `A::B`, we will want to check the
1067 // where-clauses in scope. So we will try to unify `A::B`
1068 // with `A::B`, which can trigger a recursive
1071 debug!("found cache entry: in-progress");
1073 // Cache that normalizing this projection resulted in a cycle. This
1074 // should ensure that, unless this happens within a snapshot that's
1075 // rolled back, fulfillment or evaluation will notice the cycle.
1078 infcx.inner.borrow_mut().projection_cache().recur(cache_key);
1080 return Err(InProgress);
1082 Err(ProjectionCacheEntry::Recur) => {
1083 debug!("recur cache");
1084 return Err(InProgress);
1086 Err(ProjectionCacheEntry::NormalizedTy { ty, complete: _ }) => {
1087 // This is the hottest path in this function.
1089 // If we find the value in the cache, then return it along
1090 // with the obligations that went along with it. Note
1091 // that, when using a fulfillment context, these
1092 // obligations could in principle be ignored: they have
1093 // already been registered when the cache entry was
1094 // created (and hence the new ones will quickly be
1095 // discarded as duplicated). But when doing trait
1096 // evaluation this is not the case, and dropping the trait
1097 // evaluations can causes ICEs (e.g., #43132).
1098 debug!(?ty, "found normalized ty");
1099 obligations.extend(ty.obligations);
1100 return Ok(Some(ty.value));
1102 Err(ProjectionCacheEntry::Error) => {
1103 debug!("opt_normalize_projection_type: found error");
1104 let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth);
1105 obligations.extend(result.obligations);
1106 return Ok(Some(result.value.into()));
1110 let obligation = Obligation::with_depth(cause.clone(), depth, param_env, projection_ty);
1112 match project(selcx, &obligation) {
1113 Ok(Projected::Progress(Progress {
1114 term: projected_term,
1115 obligations: mut projected_obligations,
1117 // if projection succeeded, then what we get out of this
1118 // is also non-normalized (consider: it was derived from
1119 // an impl, where-clause etc) and hence we must
1122 let projected_term = selcx.infcx().resolve_vars_if_possible(projected_term);
1124 let mut result = if projected_term.has_projections() {
1125 let mut normalizer = AssocTypeNormalizer::new(
1130 &mut projected_obligations,
1132 let normalized_ty = normalizer.fold(projected_term);
1134 Normalized { value: normalized_ty, obligations: projected_obligations }
1136 Normalized { value: projected_term, obligations: projected_obligations }
1139 let mut deduped: SsoHashSet<_> = Default::default();
1140 result.obligations.drain_filter(|projected_obligation| {
1141 if !deduped.insert(projected_obligation.clone()) {
1148 infcx.inner.borrow_mut().projection_cache().insert_term(cache_key, result.clone());
1150 obligations.extend(result.obligations);
1151 Ok(Some(result.value))
1153 Ok(Projected::NoProgress(projected_ty)) => {
1154 let result = Normalized { value: projected_ty, obligations: vec![] };
1156 infcx.inner.borrow_mut().projection_cache().insert_term(cache_key, result.clone());
1158 // No need to extend `obligations`.
1159 Ok(Some(result.value))
1161 Err(ProjectionError::TooManyCandidates) => {
1162 debug!("opt_normalize_projection_type: too many candidates");
1164 infcx.inner.borrow_mut().projection_cache().ambiguous(cache_key);
1168 Err(ProjectionError::TraitSelectionError(_)) => {
1169 debug!("opt_normalize_projection_type: ERROR");
1170 // if we got an error processing the `T as Trait` part,
1171 // just return `ty::err` but add the obligation `T :
1172 // Trait`, which when processed will cause the error to be
1176 infcx.inner.borrow_mut().projection_cache().error(cache_key);
1178 let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth);
1179 obligations.extend(result.obligations);
1180 Ok(Some(result.value.into()))
1185 /// If we are projecting `<T as Trait>::Item`, but `T: Trait` does not
1186 /// hold. In various error cases, we cannot generate a valid
1187 /// normalized projection. Therefore, we create an inference variable
1188 /// return an associated obligation that, when fulfilled, will lead to
1191 /// Note that we used to return `Error` here, but that was quite
1192 /// dubious -- the premise was that an error would *eventually* be
1193 /// reported, when the obligation was processed. But in general once
1194 /// you see an `Error` you are supposed to be able to assume that an
1195 /// error *has been* reported, so that you can take whatever heuristic
1196 /// paths you want to take. To make things worse, it was possible for
1197 /// cycles to arise, where you basically had a setup like `<MyType<$0>
1198 /// as Trait>::Foo == $0`. Here, normalizing `<MyType<$0> as
1199 /// Trait>::Foo> to `[type error]` would lead to an obligation of
1200 /// `<MyType<[type error]> as Trait>::Foo`. We are supposed to report
1201 /// an error for this obligation, but we legitimately should not,
1202 /// because it contains `[type error]`. Yuck! (See issue #29857 for
1203 /// one case where this arose.)
1204 fn normalize_to_error<'a, 'tcx>(
1205 selcx: &mut SelectionContext<'a, 'tcx>,
1206 param_env: ty::ParamEnv<'tcx>,
1207 projection_ty: ty::ProjectionTy<'tcx>,
1208 cause: ObligationCause<'tcx>,
1210 ) -> NormalizedTy<'tcx> {
1211 let trait_ref = ty::Binder::dummy(projection_ty.trait_ref(selcx.tcx()));
1212 let trait_obligation = Obligation {
1214 recursion_depth: depth,
1216 predicate: trait_ref.without_const().to_predicate(selcx.tcx()),
1218 let tcx = selcx.infcx().tcx;
1219 let def_id = projection_ty.item_def_id;
1220 let new_value = selcx.infcx().next_ty_var(TypeVariableOrigin {
1221 kind: TypeVariableOriginKind::NormalizeProjectionType,
1222 span: tcx.def_span(def_id),
1224 Normalized { value: new_value, obligations: vec![trait_obligation] }
1227 enum Projected<'tcx> {
1228 Progress(Progress<'tcx>),
1229 NoProgress(ty::Term<'tcx>),
1232 struct Progress<'tcx> {
1233 term: ty::Term<'tcx>,
1234 obligations: Vec<PredicateObligation<'tcx>>,
1237 impl<'tcx> Progress<'tcx> {
1238 fn error(tcx: TyCtxt<'tcx>) -> Self {
1239 Progress { term: tcx.ty_error().into(), obligations: vec![] }
1242 fn with_addl_obligations(mut self, mut obligations: Vec<PredicateObligation<'tcx>>) -> Self {
1243 self.obligations.append(&mut obligations);
1248 /// Computes the result of a projection type (if we can).
1251 /// - `obligation` must be fully normalized
1252 #[instrument(level = "info", skip(selcx))]
1253 fn project<'cx, 'tcx>(
1254 selcx: &mut SelectionContext<'cx, 'tcx>,
1255 obligation: &ProjectionTyObligation<'tcx>,
1256 ) -> Result<Projected<'tcx>, ProjectionError<'tcx>> {
1257 if !selcx.tcx().recursion_limit().value_within_limit(obligation.recursion_depth) {
1258 // This should really be an immediate error, but some existing code
1259 // relies on being able to recover from this.
1260 return Err(ProjectionError::TraitSelectionError(SelectionError::Overflow(
1261 OverflowError::Canonical,
1265 if obligation.predicate.references_error() {
1266 return Ok(Projected::Progress(Progress::error(selcx.tcx())));
1269 let mut candidates = ProjectionCandidateSet::None;
1271 assemble_candidate_for_impl_trait_in_trait(selcx, obligation, &mut candidates);
1273 // Make sure that the following procedures are kept in order. ParamEnv
1274 // needs to be first because it has highest priority, and Select checks
1275 // the return value of push_candidate which assumes it's ran at last.
1276 assemble_candidates_from_param_env(selcx, obligation, &mut candidates);
1278 assemble_candidates_from_trait_def(selcx, obligation, &mut candidates);
1280 assemble_candidates_from_object_ty(selcx, obligation, &mut candidates);
1282 if let ProjectionCandidateSet::Single(ProjectionCandidate::Object(_)) = candidates {
1283 // Avoid normalization cycle from selection (see
1284 // `assemble_candidates_from_object_ty`).
1285 // FIXME(lazy_normalization): Lazy normalization should save us from
1286 // having to special case this.
1288 assemble_candidates_from_impls(selcx, obligation, &mut candidates);
1292 ProjectionCandidateSet::Single(candidate) => {
1293 Ok(Projected::Progress(confirm_candidate(selcx, obligation, candidate)))
1295 ProjectionCandidateSet::None => Ok(Projected::NoProgress(
1296 // FIXME(associated_const_generics): this may need to change in the future?
1297 // need to investigate whether or not this is fine.
1300 .mk_projection(obligation.predicate.item_def_id, obligation.predicate.substs)
1303 // Error occurred while trying to processing impls.
1304 ProjectionCandidateSet::Error(e) => Err(ProjectionError::TraitSelectionError(e)),
1305 // Inherent ambiguity that prevents us from even enumerating the
1307 ProjectionCandidateSet::Ambiguous => Err(ProjectionError::TooManyCandidates),
1311 /// If the predicate's item is an `ImplTraitPlaceholder`, we do a select on the
1312 /// corresponding trait ref. If this yields an `impl`, then we're able to project
1313 /// to a concrete type, since we have an `impl`'s method to provide the RPITIT.
1314 fn assemble_candidate_for_impl_trait_in_trait<'cx, 'tcx>(
1315 selcx: &mut SelectionContext<'cx, 'tcx>,
1316 obligation: &ProjectionTyObligation<'tcx>,
1317 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1319 let tcx = selcx.tcx();
1320 if tcx.def_kind(obligation.predicate.item_def_id) == DefKind::ImplTraitPlaceholder {
1321 let trait_fn_def_id = tcx.impl_trait_in_trait_parent(obligation.predicate.item_def_id);
1322 let trait_def_id = tcx.parent(trait_fn_def_id);
1324 obligation.predicate.substs.truncate_to(tcx, tcx.generics_of(trait_def_id));
1325 // FIXME(named-returns): Binders
1326 let trait_predicate =
1327 ty::Binder::dummy(ty::TraitRef { def_id: trait_def_id, substs: trait_substs })
1328 .to_poly_trait_predicate();
1331 selcx.infcx().commit_if_ok(|_| match selcx.select(&obligation.with(trait_predicate)) {
1332 Ok(Some(super::ImplSource::UserDefined(data))) => {
1333 candidate_set.push_candidate(ProjectionCandidate::ImplTraitInTrait(data));
1337 candidate_set.mark_ambiguous();
1341 // Don't know enough about the impl to provide a useful signature
1345 debug!(error = ?e, "selection error");
1346 candidate_set.mark_error(e);
1353 /// The first thing we have to do is scan through the parameter
1354 /// environment to see whether there are any projection predicates
1355 /// there that can answer this question.
1356 fn assemble_candidates_from_param_env<'cx, 'tcx>(
1357 selcx: &mut SelectionContext<'cx, 'tcx>,
1358 obligation: &ProjectionTyObligation<'tcx>,
1359 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1361 assemble_candidates_from_predicates(
1365 ProjectionCandidate::ParamEnv,
1366 obligation.param_env.caller_bounds().iter(),
1371 /// In the case of a nested projection like `<<A as Foo>::FooT as Bar>::BarT`, we may find
1372 /// that the definition of `Foo` has some clues:
1374 /// ```ignore (illustrative)
1376 /// type FooT : Bar<BarT=i32>
1380 /// Here, for example, we could conclude that the result is `i32`.
1381 fn assemble_candidates_from_trait_def<'cx, 'tcx>(
1382 selcx: &mut SelectionContext<'cx, 'tcx>,
1383 obligation: &ProjectionTyObligation<'tcx>,
1384 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1386 debug!("assemble_candidates_from_trait_def(..)");
1388 let tcx = selcx.tcx();
1389 // Check whether the self-type is itself a projection.
1390 // If so, extract what we know from the trait and try to come up with a good answer.
1391 let bounds = match *obligation.predicate.self_ty().kind() {
1392 ty::Projection(ref data) => tcx.bound_item_bounds(data.item_def_id).subst(tcx, data.substs),
1393 ty::Opaque(def_id, substs) => tcx.bound_item_bounds(def_id).subst(tcx, substs),
1394 ty::Infer(ty::TyVar(_)) => {
1395 // If the self-type is an inference variable, then it MAY wind up
1396 // being a projected type, so induce an ambiguity.
1397 candidate_set.mark_ambiguous();
1403 assemble_candidates_from_predicates(
1407 ProjectionCandidate::TraitDef,
1413 /// In the case of a trait object like
1414 /// `<dyn Iterator<Item = ()> as Iterator>::Item` we can use the existential
1415 /// predicate in the trait object.
1417 /// We don't go through the select candidate for these bounds to avoid cycles:
1418 /// In the above case, `dyn Iterator<Item = ()>: Iterator` would create a
1419 /// nested obligation of `<dyn Iterator<Item = ()> as Iterator>::Item: Sized`,
1420 /// this then has to be normalized without having to prove
1421 /// `dyn Iterator<Item = ()>: Iterator` again.
1422 fn assemble_candidates_from_object_ty<'cx, 'tcx>(
1423 selcx: &mut SelectionContext<'cx, 'tcx>,
1424 obligation: &ProjectionTyObligation<'tcx>,
1425 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1427 debug!("assemble_candidates_from_object_ty(..)");
1429 let tcx = selcx.tcx();
1431 let self_ty = obligation.predicate.self_ty();
1432 let object_ty = selcx.infcx().shallow_resolve(self_ty);
1433 let data = match object_ty.kind() {
1434 ty::Dynamic(data, ..) => data,
1435 ty::Infer(ty::TyVar(_)) => {
1436 // If the self-type is an inference variable, then it MAY wind up
1437 // being an object type, so induce an ambiguity.
1438 candidate_set.mark_ambiguous();
1443 let env_predicates = data
1444 .projection_bounds()
1445 .filter(|bound| bound.item_def_id() == obligation.predicate.item_def_id)
1446 .map(|p| p.with_self_ty(tcx, object_ty).to_predicate(tcx));
1448 assemble_candidates_from_predicates(
1452 ProjectionCandidate::Object,
1460 skip(selcx, candidate_set, ctor, env_predicates, potentially_unnormalized_candidates)
1462 fn assemble_candidates_from_predicates<'cx, 'tcx>(
1463 selcx: &mut SelectionContext<'cx, 'tcx>,
1464 obligation: &ProjectionTyObligation<'tcx>,
1465 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1466 ctor: fn(ty::PolyProjectionPredicate<'tcx>) -> ProjectionCandidate<'tcx>,
1467 env_predicates: impl Iterator<Item = ty::Predicate<'tcx>>,
1468 potentially_unnormalized_candidates: bool,
1470 let infcx = selcx.infcx();
1471 for predicate in env_predicates {
1472 let bound_predicate = predicate.kind();
1473 if let ty::PredicateKind::Projection(data) = predicate.kind().skip_binder() {
1474 let data = bound_predicate.rebind(data);
1475 if data.projection_def_id() != obligation.predicate.item_def_id {
1479 let is_match = infcx.probe(|_| {
1480 selcx.match_projection_projections(
1483 potentially_unnormalized_candidates,
1488 ProjectionMatchesProjection::Yes => {
1489 candidate_set.push_candidate(ctor(data));
1491 if potentially_unnormalized_candidates
1492 && !obligation.predicate.has_non_region_infer()
1494 // HACK: Pick the first trait def candidate for a fully
1495 // inferred predicate. This is to allow duplicates that
1496 // differ only in normalization.
1500 ProjectionMatchesProjection::Ambiguous => {
1501 candidate_set.mark_ambiguous();
1503 ProjectionMatchesProjection::No => {}
1509 #[instrument(level = "debug", skip(selcx, obligation, candidate_set))]
1510 fn assemble_candidates_from_impls<'cx, 'tcx>(
1511 selcx: &mut SelectionContext<'cx, 'tcx>,
1512 obligation: &ProjectionTyObligation<'tcx>,
1513 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1515 // Can't assemble candidate from impl for RPITIT
1516 if selcx.tcx().def_kind(obligation.predicate.item_def_id) == DefKind::ImplTraitPlaceholder {
1520 // If we are resolving `<T as TraitRef<...>>::Item == Type`,
1521 // start out by selecting the predicate `T as TraitRef<...>`:
1522 let poly_trait_ref = ty::Binder::dummy(obligation.predicate.trait_ref(selcx.tcx()));
1523 let trait_obligation = obligation.with(poly_trait_ref.to_poly_trait_predicate());
1524 let _ = selcx.infcx().commit_if_ok(|_| {
1525 let impl_source = match selcx.select(&trait_obligation) {
1526 Ok(Some(impl_source)) => impl_source,
1528 candidate_set.mark_ambiguous();
1532 debug!(error = ?e, "selection error");
1533 candidate_set.mark_error(e);
1538 let eligible = match &impl_source {
1539 super::ImplSource::Closure(_)
1540 | super::ImplSource::Generator(_)
1541 | super::ImplSource::FnPointer(_)
1542 | super::ImplSource::TraitAlias(_) => true,
1543 super::ImplSource::UserDefined(impl_data) => {
1544 // We have to be careful when projecting out of an
1545 // impl because of specialization. If we are not in
1546 // codegen (i.e., projection mode is not "any"), and the
1547 // impl's type is declared as default, then we disable
1548 // projection (even if the trait ref is fully
1549 // monomorphic). In the case where trait ref is not
1550 // fully monomorphic (i.e., includes type parameters),
1551 // this is because those type parameters may
1552 // ultimately be bound to types from other crates that
1553 // may have specialized impls we can't see. In the
1554 // case where the trait ref IS fully monomorphic, this
1555 // is a policy decision that we made in the RFC in
1556 // order to preserve flexibility for the crate that
1557 // defined the specializable impl to specialize later
1558 // for existing types.
1560 // In either case, we handle this by not adding a
1561 // candidate for an impl if it contains a `default`
1564 // NOTE: This should be kept in sync with the similar code in
1565 // `rustc_ty_utils::instance::resolve_associated_item()`.
1567 assoc_def(selcx, impl_data.impl_def_id, obligation.predicate.item_def_id)
1568 .map_err(|ErrorGuaranteed { .. }| ())?;
1570 if node_item.is_final() {
1571 // Non-specializable items are always projectable.
1574 // Only reveal a specializable default if we're past type-checking
1575 // and the obligation is monomorphic, otherwise passes such as
1576 // transmute checking and polymorphic MIR optimizations could
1577 // get a result which isn't correct for all monomorphizations.
1578 if obligation.param_env.reveal() == Reveal::All {
1579 // NOTE(eddyb) inference variables can resolve to parameters, so
1580 // assume `poly_trait_ref` isn't monomorphic, if it contains any.
1581 let poly_trait_ref = selcx.infcx().resolve_vars_if_possible(poly_trait_ref);
1582 !poly_trait_ref.still_further_specializable()
1585 assoc_ty = ?selcx.tcx().def_path_str(node_item.item.def_id),
1586 ?obligation.predicate,
1587 "assemble_candidates_from_impls: not eligible due to default",
1593 super::ImplSource::DiscriminantKind(..) => {
1594 // While `DiscriminantKind` is automatically implemented for every type,
1595 // the concrete discriminant may not be known yet.
1597 // Any type with multiple potential discriminant types is therefore not eligible.
1598 let self_ty = selcx.infcx().shallow_resolve(obligation.predicate.self_ty());
1600 match self_ty.kind() {
1618 | ty::GeneratorWitness(..)
1621 // Integers and floats always have `u8` as their discriminant.
1622 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(..)) => true,
1628 | ty::Placeholder(..)
1630 | ty::Error(_) => false,
1633 super::ImplSource::Pointee(..) => {
1634 // While `Pointee` is automatically implemented for every type,
1635 // the concrete metadata type may not be known yet.
1637 // Any type with multiple potential metadata types is therefore not eligible.
1638 let self_ty = selcx.infcx().shallow_resolve(obligation.predicate.self_ty());
1640 let tail = selcx.tcx().struct_tail_with_normalize(
1643 // We throw away any obligations we get from this, since we normalize
1644 // and confirm these obligations once again during confirmation
1645 normalize_with_depth(
1647 obligation.param_env,
1648 obligation.cause.clone(),
1649 obligation.recursion_depth + 1,
1673 | ty::GeneratorWitness(..)
1675 // Extern types have unit metadata, according to RFC 2850
1677 // If returned by `struct_tail_without_normalization` this is a unit struct
1678 // without any fields, or not a struct, and therefore is Sized.
1680 // If returned by `struct_tail_without_normalization` this is the empty tuple.
1682 // Integers and floats are always Sized, and so have unit type metadata.
1683 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(..)) => true,
1685 // type parameters, opaques, and unnormalized projections have pointer
1686 // metadata if they're known (e.g. by the param_env) to be sized
1687 ty::Param(_) | ty::Projection(..) | ty::Opaque(..)
1688 if selcx.infcx().predicate_must_hold_modulo_regions(
1690 ty::Binder::dummy(ty::TraitRef::new(
1691 selcx.tcx().require_lang_item(LangItem::Sized, None),
1692 selcx.tcx().mk_substs_trait(self_ty, &[]),
1695 .to_predicate(selcx.tcx()),
1702 // FIXME(compiler-errors): are Bound and Placeholder types ever known sized?
1704 | ty::Projection(..)
1707 | ty::Placeholder(..)
1710 if tail.has_infer_types() {
1711 candidate_set.mark_ambiguous();
1717 super::ImplSource::Param(..) => {
1718 // This case tell us nothing about the value of an
1719 // associated type. Consider:
1722 // trait SomeTrait { type Foo; }
1723 // fn foo<T:SomeTrait>(...) { }
1726 // If the user writes `<T as SomeTrait>::Foo`, then the `T
1727 // : SomeTrait` binding does not help us decide what the
1728 // type `Foo` is (at least, not more specifically than
1729 // what we already knew).
1731 // But wait, you say! What about an example like this:
1734 // fn bar<T:SomeTrait<Foo=usize>>(...) { ... }
1737 // Doesn't the `T : SomeTrait<Foo=usize>` predicate help
1738 // resolve `T::Foo`? And of course it does, but in fact
1739 // that single predicate is desugared into two predicates
1740 // in the compiler: a trait predicate (`T : SomeTrait`) and a
1741 // projection. And the projection where clause is handled
1742 // in `assemble_candidates_from_param_env`.
1745 super::ImplSource::Object(_) => {
1746 // Handled by the `Object` projection candidate. See
1747 // `assemble_candidates_from_object_ty` for an explanation of
1748 // why we special case object types.
1751 super::ImplSource::AutoImpl(..)
1752 | super::ImplSource::Builtin(..)
1753 | super::ImplSource::TraitUpcasting(_)
1754 | super::ImplSource::ConstDestruct(_) => {
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 // we don't create Select candidates with this kind of resolution
1835 obligation.cause.span,
1836 "Cannot project an associated type from `{:?}`",
1843 fn confirm_generator_candidate<'cx, 'tcx>(
1844 selcx: &mut SelectionContext<'cx, 'tcx>,
1845 obligation: &ProjectionTyObligation<'tcx>,
1846 impl_source: ImplSourceGeneratorData<'tcx, PredicateObligation<'tcx>>,
1847 ) -> Progress<'tcx> {
1848 let gen_sig = impl_source.substs.as_generator().poly_sig();
1849 let Normalized { value: gen_sig, obligations } = normalize_with_depth(
1851 obligation.param_env,
1852 obligation.cause.clone(),
1853 obligation.recursion_depth + 1,
1857 debug!(?obligation, ?gen_sig, ?obligations, "confirm_generator_candidate");
1859 let tcx = selcx.tcx();
1861 let gen_def_id = tcx.require_lang_item(LangItem::Generator, None);
1863 let predicate = super::util::generator_trait_ref_and_outputs(
1866 obligation.predicate.self_ty(),
1869 .map_bound(|(trait_ref, yield_ty, return_ty)| {
1870 let name = tcx.associated_item(obligation.predicate.item_def_id).name;
1871 let ty = if name == sym::Return {
1873 } else if name == sym::Yield {
1879 ty::ProjectionPredicate {
1880 projection_ty: ty::ProjectionTy {
1881 substs: trait_ref.substs,
1882 item_def_id: obligation.predicate.item_def_id,
1888 confirm_param_env_candidate(selcx, obligation, predicate, false)
1889 .with_addl_obligations(impl_source.nested)
1890 .with_addl_obligations(obligations)
1893 fn confirm_discriminant_kind_candidate<'cx, 'tcx>(
1894 selcx: &mut SelectionContext<'cx, 'tcx>,
1895 obligation: &ProjectionTyObligation<'tcx>,
1896 _: ImplSourceDiscriminantKindData,
1897 ) -> Progress<'tcx> {
1898 let tcx = selcx.tcx();
1900 let self_ty = selcx.infcx().shallow_resolve(obligation.predicate.self_ty());
1901 // We get here from `poly_project_and_unify_type` which replaces bound vars
1902 // with placeholders
1903 debug_assert!(!self_ty.has_escaping_bound_vars());
1904 let substs = tcx.mk_substs([self_ty.into()].iter());
1906 let discriminant_def_id = tcx.require_lang_item(LangItem::Discriminant, None);
1908 let predicate = ty::ProjectionPredicate {
1909 projection_ty: ty::ProjectionTy { substs, item_def_id: discriminant_def_id },
1910 term: self_ty.discriminant_ty(tcx).into(),
1913 // We get here from `poly_project_and_unify_type` which replaces bound vars
1914 // with placeholders, so dummy is okay here.
1915 confirm_param_env_candidate(selcx, obligation, ty::Binder::dummy(predicate), false)
1918 fn confirm_pointee_candidate<'cx, 'tcx>(
1919 selcx: &mut SelectionContext<'cx, 'tcx>,
1920 obligation: &ProjectionTyObligation<'tcx>,
1921 _: ImplSourcePointeeData,
1922 ) -> Progress<'tcx> {
1923 let tcx = selcx.tcx();
1924 let self_ty = selcx.infcx().shallow_resolve(obligation.predicate.self_ty());
1926 let mut obligations = vec![];
1927 let (metadata_ty, check_is_sized) = self_ty.ptr_metadata_ty(tcx, |ty| {
1928 normalize_with_depth_to(
1930 obligation.param_env,
1931 obligation.cause.clone(),
1932 obligation.recursion_depth + 1,
1938 let sized_predicate = ty::Binder::dummy(ty::TraitRef::new(
1939 tcx.require_lang_item(LangItem::Sized, None),
1940 tcx.mk_substs_trait(self_ty, &[]),
1944 obligations.push(Obligation::new(
1945 obligation.cause.clone(),
1946 obligation.param_env,
1951 let substs = tcx.mk_substs([self_ty.into()].iter());
1952 let metadata_def_id = tcx.require_lang_item(LangItem::Metadata, None);
1954 let predicate = ty::ProjectionPredicate {
1955 projection_ty: ty::ProjectionTy { substs, item_def_id: metadata_def_id },
1956 term: metadata_ty.into(),
1959 confirm_param_env_candidate(selcx, obligation, ty::Binder::dummy(predicate), false)
1960 .with_addl_obligations(obligations)
1963 fn confirm_fn_pointer_candidate<'cx, 'tcx>(
1964 selcx: &mut SelectionContext<'cx, 'tcx>,
1965 obligation: &ProjectionTyObligation<'tcx>,
1966 fn_pointer_impl_source: ImplSourceFnPointerData<'tcx, PredicateObligation<'tcx>>,
1967 ) -> Progress<'tcx> {
1968 let fn_type = selcx.infcx().shallow_resolve(fn_pointer_impl_source.fn_ty);
1969 let sig = fn_type.fn_sig(selcx.tcx());
1970 let Normalized { value: sig, obligations } = normalize_with_depth(
1972 obligation.param_env,
1973 obligation.cause.clone(),
1974 obligation.recursion_depth + 1,
1978 confirm_callable_candidate(selcx, obligation, sig, util::TupleArgumentsFlag::Yes)
1979 .with_addl_obligations(fn_pointer_impl_source.nested)
1980 .with_addl_obligations(obligations)
1983 fn confirm_closure_candidate<'cx, 'tcx>(
1984 selcx: &mut SelectionContext<'cx, 'tcx>,
1985 obligation: &ProjectionTyObligation<'tcx>,
1986 impl_source: ImplSourceClosureData<'tcx, PredicateObligation<'tcx>>,
1987 ) -> Progress<'tcx> {
1988 let closure_sig = impl_source.substs.as_closure().sig();
1989 let Normalized { value: closure_sig, obligations } = normalize_with_depth(
1991 obligation.param_env,
1992 obligation.cause.clone(),
1993 obligation.recursion_depth + 1,
1997 debug!(?obligation, ?closure_sig, ?obligations, "confirm_closure_candidate");
1999 confirm_callable_candidate(selcx, obligation, closure_sig, util::TupleArgumentsFlag::No)
2000 .with_addl_obligations(impl_source.nested)
2001 .with_addl_obligations(obligations)
2004 fn confirm_callable_candidate<'cx, 'tcx>(
2005 selcx: &mut SelectionContext<'cx, 'tcx>,
2006 obligation: &ProjectionTyObligation<'tcx>,
2007 fn_sig: ty::PolyFnSig<'tcx>,
2008 flag: util::TupleArgumentsFlag,
2009 ) -> Progress<'tcx> {
2010 let tcx = selcx.tcx();
2012 debug!(?obligation, ?fn_sig, "confirm_callable_candidate");
2014 let fn_once_def_id = tcx.require_lang_item(LangItem::FnOnce, None);
2015 let fn_once_output_def_id = tcx.require_lang_item(LangItem::FnOnceOutput, None);
2017 let predicate = super::util::closure_trait_ref_and_return_type(
2020 obligation.predicate.self_ty(),
2024 .map_bound(|(trait_ref, ret_type)| ty::ProjectionPredicate {
2025 projection_ty: ty::ProjectionTy {
2026 substs: trait_ref.substs,
2027 item_def_id: fn_once_output_def_id,
2029 term: ret_type.into(),
2032 confirm_param_env_candidate(selcx, obligation, predicate, true)
2035 fn confirm_param_env_candidate<'cx, 'tcx>(
2036 selcx: &mut SelectionContext<'cx, 'tcx>,
2037 obligation: &ProjectionTyObligation<'tcx>,
2038 poly_cache_entry: ty::PolyProjectionPredicate<'tcx>,
2039 potentially_unnormalized_candidate: bool,
2040 ) -> Progress<'tcx> {
2041 let infcx = selcx.infcx();
2042 let cause = &obligation.cause;
2043 let param_env = obligation.param_env;
2045 let cache_entry = infcx.replace_bound_vars_with_fresh_vars(
2047 LateBoundRegionConversionTime::HigherRankedType,
2051 let cache_projection = cache_entry.projection_ty;
2052 let mut nested_obligations = Vec::new();
2053 let obligation_projection = obligation.predicate;
2054 let obligation_projection = ensure_sufficient_stack(|| {
2055 normalize_with_depth_to(
2057 obligation.param_env,
2058 obligation.cause.clone(),
2059 obligation.recursion_depth + 1,
2060 obligation_projection,
2061 &mut nested_obligations,
2064 let cache_projection = if potentially_unnormalized_candidate {
2065 ensure_sufficient_stack(|| {
2066 normalize_with_depth_to(
2068 obligation.param_env,
2069 obligation.cause.clone(),
2070 obligation.recursion_depth + 1,
2072 &mut nested_obligations,
2079 debug!(?cache_projection, ?obligation_projection);
2081 match infcx.at(cause, param_env).eq(cache_projection, obligation_projection) {
2082 Ok(InferOk { value: _, obligations }) => {
2083 nested_obligations.extend(obligations);
2084 assoc_ty_own_obligations(selcx, obligation, &mut nested_obligations);
2085 // FIXME(associated_const_equality): Handle consts here as well? Maybe this progress type should just take
2087 Progress { term: cache_entry.term, obligations: nested_obligations }
2091 "Failed to unify obligation `{:?}` with poly_projection `{:?}`: {:?}",
2092 obligation, poly_cache_entry, e,
2094 debug!("confirm_param_env_candidate: {}", msg);
2095 let err = infcx.tcx.ty_error_with_message(obligation.cause.span, &msg);
2096 Progress { term: err.into(), obligations: vec![] }
2101 fn confirm_impl_candidate<'cx, 'tcx>(
2102 selcx: &mut SelectionContext<'cx, 'tcx>,
2103 obligation: &ProjectionTyObligation<'tcx>,
2104 impl_impl_source: ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>>,
2105 ) -> Progress<'tcx> {
2106 let tcx = selcx.tcx();
2108 let ImplSourceUserDefinedData { impl_def_id, substs, mut nested } = impl_impl_source;
2109 let assoc_item_id = obligation.predicate.item_def_id;
2110 let trait_def_id = tcx.trait_id_of_impl(impl_def_id).unwrap();
2112 let param_env = obligation.param_env;
2113 let Ok(assoc_ty) = assoc_def(selcx, impl_def_id, assoc_item_id) else {
2114 return Progress { term: tcx.ty_error().into(), obligations: nested };
2117 if !assoc_ty.item.defaultness(tcx).has_value() {
2118 // This means that the impl is missing a definition for the
2119 // associated type. This error will be reported by the type
2120 // checker method `check_impl_items_against_trait`, so here we
2121 // just return Error.
2123 "confirm_impl_candidate: no associated type {:?} for {:?}",
2124 assoc_ty.item.name, obligation.predicate
2126 return Progress { term: tcx.ty_error().into(), obligations: nested };
2128 // If we're trying to normalize `<Vec<u32> as X>::A<S>` using
2129 //`impl<T> X for Vec<T> { type A<Y> = Box<Y>; }`, then:
2131 // * `obligation.predicate.substs` is `[Vec<u32>, S]`
2132 // * `substs` is `[u32]`
2133 // * `substs` ends up as `[u32, S]`
2134 let substs = obligation.predicate.substs.rebase_onto(tcx, trait_def_id, substs);
2136 translate_substs(selcx.infcx(), param_env, impl_def_id, substs, assoc_ty.defining_node);
2137 let ty = tcx.bound_type_of(assoc_ty.item.def_id);
2138 let is_const = matches!(tcx.def_kind(assoc_ty.item.def_id), DefKind::AssocConst);
2139 let term: ty::EarlyBinder<ty::Term<'tcx>> = if is_const {
2140 let identity_substs =
2141 crate::traits::InternalSubsts::identity_for_item(tcx, assoc_ty.item.def_id);
2142 let did = ty::WithOptConstParam::unknown(assoc_ty.item.def_id);
2143 let kind = ty::ConstKind::Unevaluated(ty::UnevaluatedConst::new(did, identity_substs));
2144 ty.map_bound(|ty| tcx.mk_const(ty::ConstS { ty, kind }).into())
2146 ty.map_bound(|ty| ty.into())
2148 if !check_substs_compatible(tcx, &assoc_ty.item, substs) {
2149 let err = tcx.ty_error_with_message(
2150 obligation.cause.span,
2151 "impl item and trait item have different parameters",
2153 Progress { term: err.into(), obligations: nested }
2155 assoc_ty_own_obligations(selcx, obligation, &mut nested);
2156 Progress { term: term.subst(tcx, substs), obligations: nested }
2160 // Verify that the trait item and its implementation have compatible substs lists
2161 fn check_substs_compatible<'tcx>(
2163 assoc_ty: &ty::AssocItem,
2164 substs: ty::SubstsRef<'tcx>,
2166 fn check_substs_compatible_inner<'tcx>(
2168 generics: &'tcx ty::Generics,
2169 args: &'tcx [ty::GenericArg<'tcx>],
2171 if generics.count() != args.len() {
2175 let (parent_args, own_args) = args.split_at(generics.parent_count);
2177 if let Some(parent) = generics.parent
2178 && let parent_generics = tcx.generics_of(parent)
2179 && !check_substs_compatible_inner(tcx, parent_generics, parent_args) {
2183 for (param, arg) in std::iter::zip(&generics.params, own_args) {
2184 match (¶m.kind, arg.unpack()) {
2185 (ty::GenericParamDefKind::Type { .. }, ty::GenericArgKind::Type(_))
2186 | (ty::GenericParamDefKind::Lifetime, ty::GenericArgKind::Lifetime(_))
2187 | (ty::GenericParamDefKind::Const { .. }, ty::GenericArgKind::Const(_)) => {}
2195 check_substs_compatible_inner(tcx, tcx.generics_of(assoc_ty.def_id), substs.as_slice())
2198 fn confirm_impl_trait_in_trait_candidate<'tcx>(
2199 selcx: &mut SelectionContext<'_, 'tcx>,
2200 obligation: &ProjectionTyObligation<'tcx>,
2201 data: ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>>,
2202 ) -> Progress<'tcx> {
2203 let tcx = selcx.tcx();
2204 let mut obligations = data.nested;
2206 let trait_fn_def_id = tcx.impl_trait_in_trait_parent(obligation.predicate.item_def_id);
2207 let Ok(leaf_def) = assoc_def(selcx, data.impl_def_id, trait_fn_def_id) else {
2208 return Progress { term: tcx.ty_error().into(), obligations };
2210 if !leaf_def.item.defaultness(tcx).has_value() {
2211 return Progress { term: tcx.ty_error().into(), obligations };
2214 let impl_fn_def_id = leaf_def.item.def_id;
2215 let impl_fn_substs = obligation.predicate.substs.rebase_onto(tcx, trait_fn_def_id, data.substs);
2217 let cause = ObligationCause::new(
2218 obligation.cause.span,
2219 obligation.cause.body_id,
2220 super::ItemObligation(impl_fn_def_id),
2222 let predicates = normalize_with_depth_to(
2224 obligation.param_env,
2226 obligation.recursion_depth + 1,
2227 tcx.predicates_of(impl_fn_def_id).instantiate(tcx, impl_fn_substs),
2230 obligations.extend(std::iter::zip(predicates.predicates, predicates.spans).map(
2232 Obligation::with_depth(
2233 ObligationCause::new(
2234 obligation.cause.span,
2235 obligation.cause.body_id,
2236 if span.is_dummy() {
2237 super::ItemObligation(impl_fn_def_id)
2239 super::BindingObligation(impl_fn_def_id, span)
2242 obligation.recursion_depth + 1,
2243 obligation.param_env,
2249 let ty = super::normalize_to(
2251 obligation.param_env,
2253 tcx.bound_trait_impl_trait_tys(impl_fn_def_id)
2255 tys.map_or_else(|_| tcx.ty_error(), |tys| tys[&obligation.predicate.item_def_id])
2257 .subst(tcx, impl_fn_substs),
2261 Progress { term: ty.into(), obligations }
2264 // Get obligations corresponding to the predicates from the where-clause of the
2265 // associated type itself.
2266 fn assoc_ty_own_obligations<'cx, 'tcx>(
2267 selcx: &mut SelectionContext<'cx, 'tcx>,
2268 obligation: &ProjectionTyObligation<'tcx>,
2269 nested: &mut Vec<PredicateObligation<'tcx>>,
2271 let tcx = selcx.tcx();
2272 for predicate in tcx
2273 .predicates_of(obligation.predicate.item_def_id)
2274 .instantiate_own(tcx, obligation.predicate.substs)
2277 let normalized = normalize_with_depth_to(
2279 obligation.param_env,
2280 obligation.cause.clone(),
2281 obligation.recursion_depth + 1,
2285 nested.push(Obligation::with_depth(
2286 obligation.cause.clone(),
2287 obligation.recursion_depth + 1,
2288 obligation.param_env,
2294 /// Locate the definition of an associated type in the specialization hierarchy,
2295 /// starting from the given impl.
2297 /// Based on the "projection mode", this lookup may in fact only examine the
2298 /// topmost impl. See the comments for `Reveal` for more details.
2300 selcx: &SelectionContext<'_, '_>,
2302 assoc_def_id: DefId,
2303 ) -> Result<specialization_graph::LeafDef, ErrorGuaranteed> {
2304 let tcx = selcx.tcx();
2305 let trait_def_id = tcx.impl_trait_ref(impl_def_id).unwrap().def_id;
2306 let trait_def = tcx.trait_def(trait_def_id);
2308 // This function may be called while we are still building the
2309 // specialization graph that is queried below (via TraitDef::ancestors()),
2310 // so, in order to avoid unnecessary infinite recursion, we manually look
2311 // for the associated item at the given impl.
2312 // If there is no such item in that impl, this function will fail with a
2313 // cycle error if the specialization graph is currently being built.
2314 if let Some(&impl_item_id) = tcx.impl_item_implementor_ids(impl_def_id).get(&assoc_def_id) {
2315 let item = tcx.associated_item(impl_item_id);
2316 let impl_node = specialization_graph::Node::Impl(impl_def_id);
2317 return Ok(specialization_graph::LeafDef {
2319 defining_node: impl_node,
2320 finalizing_node: if item.defaultness(tcx).is_default() {
2328 let ancestors = trait_def.ancestors(tcx, impl_def_id)?;
2329 if let Some(assoc_item) = ancestors.leaf_def(tcx, assoc_def_id) {
2332 // This is saying that neither the trait nor
2333 // the impl contain a definition for this
2334 // associated type. Normally this situation
2335 // could only arise through a compiler bug --
2336 // if the user wrote a bad item name, it
2337 // should have failed in astconv.
2339 "No associated type `{}` for {}",
2340 tcx.item_name(assoc_def_id),
2341 tcx.def_path_str(impl_def_id)
2346 pub(crate) trait ProjectionCacheKeyExt<'cx, 'tcx>: Sized {
2347 fn from_poly_projection_predicate(
2348 selcx: &mut SelectionContext<'cx, 'tcx>,
2349 predicate: ty::PolyProjectionPredicate<'tcx>,
2353 impl<'cx, 'tcx> ProjectionCacheKeyExt<'cx, 'tcx> for ProjectionCacheKey<'tcx> {
2354 fn from_poly_projection_predicate(
2355 selcx: &mut SelectionContext<'cx, 'tcx>,
2356 predicate: ty::PolyProjectionPredicate<'tcx>,
2358 let infcx = selcx.infcx();
2359 // We don't do cross-snapshot caching of obligations with escaping regions,
2360 // so there's no cache key to use
2361 predicate.no_bound_vars().map(|predicate| {
2362 ProjectionCacheKey::new(
2363 // We don't attempt to match up with a specific type-variable state
2364 // from a specific call to `opt_normalize_projection_type` - if
2365 // there's no precise match, the original cache entry is "stranded"
2367 infcx.resolve_vars_if_possible(predicate.projection_ty),