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(ImplTraitInTraitCandidate<'tcx>),
78 #[derive(PartialEq, Eq, Debug)]
79 enum ImplTraitInTraitCandidate<'tcx> {
80 // The `impl Trait` from a trait function's default body
82 // A concrete type provided from a trait's `impl Trait` from an impl
83 Impl(ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>>),
86 enum ProjectionCandidateSet<'tcx> {
88 Single(ProjectionCandidate<'tcx>),
90 Error(SelectionError<'tcx>),
93 impl<'tcx> ProjectionCandidateSet<'tcx> {
94 fn mark_ambiguous(&mut self) {
95 *self = ProjectionCandidateSet::Ambiguous;
98 fn mark_error(&mut self, err: SelectionError<'tcx>) {
99 *self = ProjectionCandidateSet::Error(err);
102 // Returns true if the push was successful, or false if the candidate
103 // was discarded -- this could be because of ambiguity, or because
104 // a higher-priority candidate is already there.
105 fn push_candidate(&mut self, candidate: ProjectionCandidate<'tcx>) -> bool {
106 use self::ProjectionCandidate::*;
107 use self::ProjectionCandidateSet::*;
109 // This wacky variable is just used to try and
110 // make code readable and avoid confusing paths.
111 // It is assigned a "value" of `()` only on those
112 // paths in which we wish to convert `*self` to
113 // ambiguous (and return false, because the candidate
114 // was not used). On other paths, it is not assigned,
115 // and hence if those paths *could* reach the code that
116 // comes after the match, this fn would not compile.
117 let convert_to_ambiguous;
121 *self = Single(candidate);
126 // Duplicates can happen inside ParamEnv. In the case, we
127 // perform a lazy deduplication.
128 if current == &candidate {
132 // Prefer where-clauses. As in select, if there are multiple
133 // candidates, we prefer where-clause candidates over impls. This
134 // may seem a bit surprising, since impls are the source of
135 // "truth" in some sense, but in fact some of the impls that SEEM
136 // applicable are not, because of nested obligations. Where
137 // clauses are the safer choice. See the comment on
138 // `select::SelectionCandidate` and #21974 for more details.
139 match (current, candidate) {
140 (ParamEnv(..), ParamEnv(..)) => convert_to_ambiguous = (),
141 (ParamEnv(..), _) => return false,
142 (_, ParamEnv(..)) => unreachable!(),
143 (_, _) => convert_to_ambiguous = (),
147 Ambiguous | Error(..) => {
152 // We only ever get here when we moved from a single candidate
154 let () = convert_to_ambiguous;
160 /// States returned from `poly_project_and_unify_type`. Takes the place
161 /// of the old return type, which was:
162 /// ```ignore (not-rust)
164 /// Result<Option<Vec<PredicateObligation<'tcx>>>, InProgress>,
165 /// MismatchedProjectionTypes<'tcx>,
168 pub(super) enum ProjectAndUnifyResult<'tcx> {
169 /// The projection bound holds subject to the given obligations. If the
170 /// projection cannot be normalized because the required trait bound does
171 /// not hold, this is returned, with `obligations` being a predicate that
172 /// cannot be proven.
173 Holds(Vec<PredicateObligation<'tcx>>),
174 /// The projection cannot be normalized due to ambiguity. Resolving some
175 /// inference variables in the projection may fix this.
177 /// The project cannot be normalized because `poly_project_and_unify_type`
178 /// is called recursively while normalizing the same projection.
180 // the projection can be normalized, but is not equal to the expected type.
181 // Returns the type error that arose from the mismatch.
182 MismatchedProjectionTypes(MismatchedProjectionTypes<'tcx>),
185 /// Evaluates constraints of the form:
186 /// ```ignore (not-rust)
187 /// for<...> <T as Trait>::U == V
189 /// If successful, this may result in additional obligations. Also returns
190 /// the projection cache key used to track these additional obligations.
191 #[instrument(level = "debug", skip(selcx))]
192 pub(super) fn poly_project_and_unify_type<'cx, 'tcx>(
193 selcx: &mut SelectionContext<'cx, 'tcx>,
194 obligation: &PolyProjectionObligation<'tcx>,
195 ) -> ProjectAndUnifyResult<'tcx> {
196 let infcx = selcx.infcx();
197 let r = infcx.commit_if_ok(|_snapshot| {
198 let old_universe = infcx.universe();
199 let placeholder_predicate =
200 infcx.replace_bound_vars_with_placeholders(obligation.predicate);
201 let new_universe = infcx.universe();
203 let placeholder_obligation = obligation.with(infcx.tcx, placeholder_predicate);
204 match project_and_unify_type(selcx, &placeholder_obligation) {
205 ProjectAndUnifyResult::MismatchedProjectionTypes(e) => Err(e),
206 ProjectAndUnifyResult::Holds(obligations)
207 if old_universe != new_universe
208 && selcx.tcx().features().generic_associated_types_extended =>
210 // If the `generic_associated_types_extended` feature is active, then we ignore any
211 // obligations references lifetimes from any universe greater than or equal to the
212 // universe just created. Otherwise, we can end up with something like `for<'a> I: 'a`,
213 // which isn't quite what we want. Ideally, we want either an implied
214 // `for<'a where I: 'a> I: 'a` or we want to "lazily" check these hold when we
215 // substitute concrete regions. There is design work to be done here; until then,
216 // however, this allows experimenting potential GAT features without running into
217 // well-formedness issues.
218 let new_obligations = obligations
220 .filter(|obligation| {
221 let mut visitor = MaxUniverse::new();
222 obligation.predicate.visit_with(&mut visitor);
223 visitor.max_universe() < new_universe
226 Ok(ProjectAndUnifyResult::Holds(new_obligations))
234 Err(err) => ProjectAndUnifyResult::MismatchedProjectionTypes(err),
238 /// Evaluates constraints of the form:
239 /// ```ignore (not-rust)
240 /// <T as Trait>::U == V
242 /// If successful, this may result in additional obligations.
244 /// See [poly_project_and_unify_type] for an explanation of the return value.
245 #[instrument(level = "debug", skip(selcx))]
246 fn project_and_unify_type<'cx, 'tcx>(
247 selcx: &mut SelectionContext<'cx, 'tcx>,
248 obligation: &ProjectionObligation<'tcx>,
249 ) -> ProjectAndUnifyResult<'tcx> {
250 let mut obligations = vec![];
252 let infcx = selcx.infcx();
253 let normalized = match opt_normalize_projection_type(
255 obligation.param_env,
256 obligation.predicate.projection_ty,
257 obligation.cause.clone(),
258 obligation.recursion_depth,
262 Ok(None) => return ProjectAndUnifyResult::FailedNormalization,
263 Err(InProgress) => return ProjectAndUnifyResult::Recursive,
265 debug!(?normalized, ?obligations, "project_and_unify_type result");
266 let actual = obligation.predicate.term;
267 // For an example where this is necessary see src/test/ui/impl-trait/nested-return-type2.rs
268 // This allows users to omit re-mentioning all bounds on an associated type and just use an
269 // `impl Trait` for the assoc type to add more bounds.
270 let InferOk { value: actual, obligations: new } =
271 selcx.infcx().replace_opaque_types_with_inference_vars(
273 obligation.cause.body_id,
274 obligation.cause.span,
275 obligation.param_env,
277 obligations.extend(new);
279 match infcx.at(&obligation.cause, obligation.param_env).eq(normalized, actual) {
280 Ok(InferOk { obligations: inferred_obligations, value: () }) => {
281 obligations.extend(inferred_obligations);
282 ProjectAndUnifyResult::Holds(obligations)
285 debug!("equating types encountered error {:?}", err);
286 ProjectAndUnifyResult::MismatchedProjectionTypes(MismatchedProjectionTypes { err })
291 /// Normalizes any associated type projections in `value`, replacing
292 /// them with a fully resolved type where possible. The return value
293 /// combines the normalized result and any additional obligations that
294 /// were incurred as result.
295 pub fn normalize<'a, 'b, 'tcx, T>(
296 selcx: &'a mut SelectionContext<'b, 'tcx>,
297 param_env: ty::ParamEnv<'tcx>,
298 cause: ObligationCause<'tcx>,
300 ) -> Normalized<'tcx, T>
302 T: TypeFoldable<'tcx>,
304 let mut obligations = Vec::new();
305 let value = normalize_to(selcx, param_env, cause, value, &mut obligations);
306 Normalized { value, obligations }
309 pub fn normalize_to<'a, 'b, 'tcx, T>(
310 selcx: &'a mut SelectionContext<'b, 'tcx>,
311 param_env: ty::ParamEnv<'tcx>,
312 cause: ObligationCause<'tcx>,
314 obligations: &mut Vec<PredicateObligation<'tcx>>,
317 T: TypeFoldable<'tcx>,
319 normalize_with_depth_to(selcx, param_env, cause, 0, value, obligations)
322 /// As `normalize`, but with a custom depth.
323 pub fn normalize_with_depth<'a, 'b, 'tcx, T>(
324 selcx: &'a mut SelectionContext<'b, 'tcx>,
325 param_env: ty::ParamEnv<'tcx>,
326 cause: ObligationCause<'tcx>,
329 ) -> Normalized<'tcx, T>
331 T: TypeFoldable<'tcx>,
333 let mut obligations = Vec::new();
334 let value = normalize_with_depth_to(selcx, param_env, cause, depth, value, &mut obligations);
335 Normalized { value, obligations }
338 #[instrument(level = "info", skip(selcx, param_env, cause, obligations))]
339 pub fn normalize_with_depth_to<'a, 'b, 'tcx, T>(
340 selcx: &'a mut SelectionContext<'b, 'tcx>,
341 param_env: ty::ParamEnv<'tcx>,
342 cause: ObligationCause<'tcx>,
345 obligations: &mut Vec<PredicateObligation<'tcx>>,
348 T: TypeFoldable<'tcx>,
350 debug!(obligations.len = obligations.len());
351 let mut normalizer = AssocTypeNormalizer::new(selcx, param_env, cause, depth, obligations);
352 let result = ensure_sufficient_stack(|| normalizer.fold(value));
353 debug!(?result, obligations.len = normalizer.obligations.len());
354 debug!(?normalizer.obligations,);
358 #[instrument(level = "info", skip(selcx, param_env, cause, obligations))]
359 pub fn try_normalize_with_depth_to<'a, 'b, 'tcx, T>(
360 selcx: &'a mut SelectionContext<'b, 'tcx>,
361 param_env: ty::ParamEnv<'tcx>,
362 cause: ObligationCause<'tcx>,
365 obligations: &mut Vec<PredicateObligation<'tcx>>,
368 T: TypeFoldable<'tcx>,
370 debug!(obligations.len = obligations.len());
371 let mut normalizer = AssocTypeNormalizer::new_without_eager_inference_replacement(
378 let result = ensure_sufficient_stack(|| normalizer.fold(value));
379 debug!(?result, obligations.len = normalizer.obligations.len());
380 debug!(?normalizer.obligations,);
384 pub(crate) fn needs_normalization<'tcx, T: TypeVisitable<'tcx>>(value: &T, reveal: Reveal) -> bool {
386 Reveal::UserFacing => value
387 .has_type_flags(ty::TypeFlags::HAS_TY_PROJECTION | ty::TypeFlags::HAS_CT_PROJECTION),
388 Reveal::All => value.has_type_flags(
389 ty::TypeFlags::HAS_TY_PROJECTION
390 | ty::TypeFlags::HAS_TY_OPAQUE
391 | ty::TypeFlags::HAS_CT_PROJECTION,
396 struct AssocTypeNormalizer<'a, 'b, 'tcx> {
397 selcx: &'a mut SelectionContext<'b, 'tcx>,
398 param_env: ty::ParamEnv<'tcx>,
399 cause: ObligationCause<'tcx>,
400 obligations: &'a mut Vec<PredicateObligation<'tcx>>,
402 universes: Vec<Option<ty::UniverseIndex>>,
403 /// If true, when a projection is unable to be completed, an inference
404 /// variable will be created and an obligation registered to project to that
405 /// inference variable. Also, constants will be eagerly evaluated.
406 eager_inference_replacement: bool,
409 impl<'a, 'b, 'tcx> AssocTypeNormalizer<'a, 'b, 'tcx> {
411 selcx: &'a mut SelectionContext<'b, 'tcx>,
412 param_env: ty::ParamEnv<'tcx>,
413 cause: ObligationCause<'tcx>,
415 obligations: &'a mut Vec<PredicateObligation<'tcx>>,
416 ) -> AssocTypeNormalizer<'a, 'b, 'tcx> {
417 AssocTypeNormalizer {
424 eager_inference_replacement: true,
428 fn new_without_eager_inference_replacement(
429 selcx: &'a mut SelectionContext<'b, 'tcx>,
430 param_env: ty::ParamEnv<'tcx>,
431 cause: ObligationCause<'tcx>,
433 obligations: &'a mut Vec<PredicateObligation<'tcx>>,
434 ) -> AssocTypeNormalizer<'a, 'b, 'tcx> {
435 AssocTypeNormalizer {
442 eager_inference_replacement: false,
446 fn fold<T: TypeFoldable<'tcx>>(&mut self, value: T) -> T {
447 let value = self.selcx.infcx().resolve_vars_if_possible(value);
451 !value.has_escaping_bound_vars(),
452 "Normalizing {:?} without wrapping in a `Binder`",
456 if !needs_normalization(&value, self.param_env.reveal()) {
459 value.fold_with(self)
464 impl<'a, 'b, 'tcx> TypeFolder<'tcx> for AssocTypeNormalizer<'a, 'b, 'tcx> {
465 fn tcx<'c>(&'c self) -> TyCtxt<'tcx> {
469 fn fold_binder<T: TypeFoldable<'tcx>>(
471 t: ty::Binder<'tcx, T>,
472 ) -> ty::Binder<'tcx, T> {
473 self.universes.push(None);
474 let t = t.super_fold_with(self);
475 self.universes.pop();
479 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
480 if !needs_normalization(&ty, self.param_env.reveal()) {
484 // We try to be a little clever here as a performance optimization in
485 // cases where there are nested projections under binders.
488 // for<'a> fn(<T as Foo>::One<'a, Box<dyn Bar<'a, Item=<T as Foo>::Two<'a>>>>)
490 // We normalize the substs on the projection before the projecting, but
491 // if we're naive, we'll
492 // replace bound vars on inner, project inner, replace placeholders on inner,
493 // replace bound vars on outer, project outer, replace placeholders on outer
495 // However, if we're a bit more clever, we can replace the bound vars
496 // on the entire type before normalizing nested projections, meaning we
497 // replace bound vars on outer, project inner,
498 // project outer, replace placeholders on outer
500 // This is possible because the inner `'a` will already be a placeholder
501 // when we need to normalize the inner projection
503 // On the other hand, this does add a bit of complexity, since we only
504 // replace bound vars if the current type is a `Projection` and we need
505 // to make sure we don't forget to fold the substs regardless.
508 // This is really important. While we *can* handle this, this has
509 // severe performance implications for large opaque types with
510 // late-bound regions. See `issue-88862` benchmark.
511 ty::Opaque(def_id, substs) => {
512 // Only normalize `impl Trait` outside of type inference, usually in codegen.
513 match self.param_env.reveal() {
514 Reveal::UserFacing => ty.super_fold_with(self),
517 let recursion_limit = self.tcx().recursion_limit();
518 if !recursion_limit.value_within_limit(self.depth) {
519 let obligation = Obligation::with_depth(
526 self.selcx.infcx().err_ctxt().report_overflow_error(&obligation, true);
529 let substs = substs.fold_with(self);
530 let generic_ty = self.tcx().bound_type_of(def_id);
531 let concrete_ty = generic_ty.subst(self.tcx(), substs);
533 let folded_ty = self.fold_ty(concrete_ty);
540 ty::Projection(data) if !data.has_escaping_bound_vars() => {
541 // This branch is *mostly* just an optimization: when we don't
542 // have escaping bound vars, we don't need to replace them with
543 // placeholders (see branch below). *Also*, we know that we can
544 // register an obligation to *later* project, since we know
545 // there won't be bound vars there.
546 let data = data.fold_with(self);
547 let normalized_ty = if self.eager_inference_replacement {
548 normalize_projection_type(
554 &mut self.obligations,
557 opt_normalize_projection_type(
563 &mut self.obligations,
567 .unwrap_or_else(|| ty.super_fold_with(self).into())
569 // For cases like #95134 we would like to catch overflows early
570 // otherwise they slip away and cause ICE.
571 let recursion_limit = self.tcx().recursion_limit();
572 if !recursion_limit.value_within_limit(self.depth)
573 // HACK: Don't overflow when running cargo doc see #100991
574 && !self.tcx().sess.opts.actually_rustdoc
576 let obligation = Obligation::with_depth(
583 self.selcx.infcx().err_ctxt().report_overflow_error(&obligation, true);
589 obligations.len = ?self.obligations.len(),
590 "AssocTypeNormalizer: normalized type"
592 normalized_ty.ty().unwrap()
595 ty::Projection(data) => {
596 // If there are escaping bound vars, we temporarily replace the
597 // bound vars with placeholders. Note though, that in the case
598 // that we still can't project for whatever reason (e.g. self
599 // type isn't known enough), we *can't* register an obligation
600 // and return an inference variable (since then that obligation
601 // would have bound vars and that's a can of worms). Instead,
602 // we just give up and fall back to pretending like we never tried!
604 // Note: this isn't necessarily the final approach here; we may
605 // want to figure out how to register obligations with escaping vars
606 // or handle this some other way.
608 let infcx = self.selcx.infcx();
609 let (data, mapped_regions, mapped_types, mapped_consts) =
610 BoundVarReplacer::replace_bound_vars(infcx, &mut self.universes, data);
611 let data = data.fold_with(self);
612 let normalized_ty = opt_normalize_projection_type(
618 &mut self.obligations,
622 .map(|term| term.ty().unwrap())
623 .map(|normalized_ty| {
624 PlaceholderReplacer::replace_placeholders(
633 .unwrap_or_else(|| ty.super_fold_with(self));
639 obligations.len = ?self.obligations.len(),
640 "AssocTypeNormalizer: normalized type"
645 _ => ty.super_fold_with(self),
649 #[instrument(skip(self), level = "debug")]
650 fn fold_const(&mut self, constant: ty::Const<'tcx>) -> ty::Const<'tcx> {
651 let tcx = self.selcx.tcx();
652 if tcx.lazy_normalization() || !needs_normalization(&constant, self.param_env.reveal()) {
655 let constant = constant.super_fold_with(self);
656 debug!(?constant, ?self.param_env);
657 with_replaced_escaping_bound_vars(
661 |constant| constant.eval(tcx, self.param_env),
667 fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
668 if p.allow_normalization() && needs_normalization(&p, self.param_env.reveal()) {
669 p.super_fold_with(self)
676 pub struct BoundVarReplacer<'me, 'tcx> {
677 infcx: &'me InferCtxt<'tcx>,
678 // These three maps track the bound variable that were replaced by placeholders. It might be
679 // nice to remove these since we already have the `kind` in the placeholder; we really just need
680 // the `var` (but we *could* bring that into scope if we were to track them as we pass them).
681 mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
682 mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy>,
683 mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
684 // The current depth relative to *this* folding, *not* the entire normalization. In other words,
685 // the depth of binders we've passed here.
686 current_index: ty::DebruijnIndex,
687 // The `UniverseIndex` of the binding levels above us. These are optional, since we are lazy:
688 // we don't actually create a universe until we see a bound var we have to replace.
689 universe_indices: &'me mut Vec<Option<ty::UniverseIndex>>,
692 /// Executes `f` on `value` after replacing all escaping bound variables with placeholders
693 /// and then replaces these placeholders with the original bound variables in the result.
695 /// In most places, bound variables should be replaced right when entering a binder, making
696 /// this function unnecessary. However, normalization currently does not do that, so we have
697 /// to do this lazily.
699 /// You should not add any additional uses of this function, at least not without first
700 /// discussing it with t-types.
702 /// FIXME(@lcnr): We may even consider experimenting with eagerly replacing bound vars during
703 /// normalization as well, at which point this function will be unnecessary and can be removed.
704 pub fn with_replaced_escaping_bound_vars<'a, 'tcx, T: TypeFoldable<'tcx>, R: TypeFoldable<'tcx>>(
705 infcx: &'a InferCtxt<'tcx>,
706 universe_indices: &'a mut Vec<Option<ty::UniverseIndex>>,
708 f: impl FnOnce(T) -> R,
710 if value.has_escaping_bound_vars() {
711 let (value, mapped_regions, mapped_types, mapped_consts) =
712 BoundVarReplacer::replace_bound_vars(infcx, universe_indices, value);
713 let result = f(value);
714 PlaceholderReplacer::replace_placeholders(
727 impl<'me, 'tcx> BoundVarReplacer<'me, 'tcx> {
728 /// Returns `Some` if we *were* able to replace bound vars. If there are any bound vars that
729 /// use a binding level above `universe_indices.len()`, we fail.
730 pub fn replace_bound_vars<T: TypeFoldable<'tcx>>(
731 infcx: &'me InferCtxt<'tcx>,
732 universe_indices: &'me mut Vec<Option<ty::UniverseIndex>>,
736 BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
737 BTreeMap<ty::PlaceholderType, ty::BoundTy>,
738 BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
740 let mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion> = BTreeMap::new();
741 let mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy> = BTreeMap::new();
742 let mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar> = BTreeMap::new();
744 let mut replacer = BoundVarReplacer {
749 current_index: ty::INNERMOST,
753 let value = value.fold_with(&mut replacer);
755 (value, replacer.mapped_regions, replacer.mapped_types, replacer.mapped_consts)
758 fn universe_for(&mut self, debruijn: ty::DebruijnIndex) -> ty::UniverseIndex {
759 let infcx = self.infcx;
761 self.universe_indices.len() + self.current_index.as_usize() - debruijn.as_usize() - 1;
762 let universe = self.universe_indices[index].unwrap_or_else(|| {
763 for i in self.universe_indices.iter_mut().take(index + 1) {
764 *i = i.or_else(|| Some(infcx.create_next_universe()))
766 self.universe_indices[index].unwrap()
772 impl<'tcx> TypeFolder<'tcx> for BoundVarReplacer<'_, 'tcx> {
773 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
777 fn fold_binder<T: TypeFoldable<'tcx>>(
779 t: ty::Binder<'tcx, T>,
780 ) -> ty::Binder<'tcx, T> {
781 self.current_index.shift_in(1);
782 let t = t.super_fold_with(self);
783 self.current_index.shift_out(1);
787 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
789 ty::ReLateBound(debruijn, _)
790 if debruijn.as_usize() + 1
791 > self.current_index.as_usize() + self.universe_indices.len() =>
793 bug!("Bound vars outside of `self.universe_indices`");
795 ty::ReLateBound(debruijn, br) if debruijn >= self.current_index => {
796 let universe = self.universe_for(debruijn);
797 let p = ty::PlaceholderRegion { universe, name: br.kind };
798 self.mapped_regions.insert(p, br);
799 self.infcx.tcx.mk_region(ty::RePlaceholder(p))
805 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
807 ty::Bound(debruijn, _)
808 if debruijn.as_usize() + 1
809 > self.current_index.as_usize() + self.universe_indices.len() =>
811 bug!("Bound vars outside of `self.universe_indices`");
813 ty::Bound(debruijn, bound_ty) if debruijn >= self.current_index => {
814 let universe = self.universe_for(debruijn);
815 let p = ty::PlaceholderType { universe, name: bound_ty.var };
816 self.mapped_types.insert(p, bound_ty);
817 self.infcx.tcx.mk_ty(ty::Placeholder(p))
819 _ if t.has_vars_bound_at_or_above(self.current_index) => t.super_fold_with(self),
824 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
826 ty::ConstKind::Bound(debruijn, _)
827 if debruijn.as_usize() + 1
828 > self.current_index.as_usize() + self.universe_indices.len() =>
830 bug!("Bound vars outside of `self.universe_indices`");
832 ty::ConstKind::Bound(debruijn, bound_const) if debruijn >= self.current_index => {
833 let universe = self.universe_for(debruijn);
834 let p = ty::PlaceholderConst { universe, name: bound_const };
835 self.mapped_consts.insert(p, bound_const);
836 self.infcx.tcx.mk_const(ty::ConstKind::Placeholder(p), ct.ty())
838 _ => ct.super_fold_with(self),
842 fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
843 if p.has_vars_bound_at_or_above(self.current_index) { p.super_fold_with(self) } else { p }
847 // The inverse of `BoundVarReplacer`: replaces placeholders with the bound vars from which they came.
848 pub struct PlaceholderReplacer<'me, 'tcx> {
849 infcx: &'me InferCtxt<'tcx>,
850 mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
851 mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy>,
852 mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
853 universe_indices: &'me [Option<ty::UniverseIndex>],
854 current_index: ty::DebruijnIndex,
857 impl<'me, 'tcx> PlaceholderReplacer<'me, 'tcx> {
858 pub fn replace_placeholders<T: TypeFoldable<'tcx>>(
859 infcx: &'me InferCtxt<'tcx>,
860 mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
861 mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy>,
862 mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
863 universe_indices: &'me [Option<ty::UniverseIndex>],
866 let mut replacer = PlaceholderReplacer {
872 current_index: ty::INNERMOST,
874 value.fold_with(&mut replacer)
878 impl<'tcx> TypeFolder<'tcx> for PlaceholderReplacer<'_, 'tcx> {
879 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
883 fn fold_binder<T: TypeFoldable<'tcx>>(
885 t: ty::Binder<'tcx, T>,
886 ) -> ty::Binder<'tcx, T> {
887 if !t.has_placeholders() && !t.has_infer_regions() {
890 self.current_index.shift_in(1);
891 let t = t.super_fold_with(self);
892 self.current_index.shift_out(1);
896 fn fold_region(&mut self, r0: ty::Region<'tcx>) -> ty::Region<'tcx> {
902 .unwrap_region_constraints()
903 .opportunistic_resolve_region(self.infcx.tcx, r0),
908 ty::RePlaceholder(p) => {
909 let replace_var = self.mapped_regions.get(&p);
911 Some(replace_var) => {
915 .position(|u| matches!(u, Some(pu) if *pu == p.universe))
916 .unwrap_or_else(|| bug!("Unexpected placeholder universe."));
917 let db = ty::DebruijnIndex::from_usize(
918 self.universe_indices.len() - index + self.current_index.as_usize() - 1,
920 self.tcx().mk_region(ty::ReLateBound(db, *replace_var))
928 debug!(?r0, ?r1, ?r2, "fold_region");
933 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
935 ty::Placeholder(p) => {
936 let replace_var = self.mapped_types.get(&p);
938 Some(replace_var) => {
942 .position(|u| matches!(u, Some(pu) if *pu == p.universe))
943 .unwrap_or_else(|| bug!("Unexpected placeholder universe."));
944 let db = ty::DebruijnIndex::from_usize(
945 self.universe_indices.len() - index + self.current_index.as_usize() - 1,
947 self.tcx().mk_ty(ty::Bound(db, *replace_var))
953 _ if ty.has_placeholders() || ty.has_infer_regions() => ty.super_fold_with(self),
958 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
959 if let ty::ConstKind::Placeholder(p) = ct.kind() {
960 let replace_var = self.mapped_consts.get(&p);
962 Some(replace_var) => {
966 .position(|u| matches!(u, Some(pu) if *pu == p.universe))
967 .unwrap_or_else(|| bug!("Unexpected placeholder universe."));
968 let db = ty::DebruijnIndex::from_usize(
969 self.universe_indices.len() - index + self.current_index.as_usize() - 1,
971 self.tcx().mk_const(ty::ConstKind::Bound(db, *replace_var), ct.ty())
976 ct.super_fold_with(self)
981 /// The guts of `normalize`: normalize a specific projection like `<T
982 /// as Trait>::Item`. The result is always a type (and possibly
983 /// additional obligations). If ambiguity arises, which implies that
984 /// there are unresolved type variables in the projection, we will
985 /// substitute a fresh type variable `$X` and generate a new
986 /// obligation `<T as Trait>::Item == $X` for later.
987 pub fn normalize_projection_type<'a, 'b, 'tcx>(
988 selcx: &'a mut SelectionContext<'b, 'tcx>,
989 param_env: ty::ParamEnv<'tcx>,
990 projection_ty: ty::ProjectionTy<'tcx>,
991 cause: ObligationCause<'tcx>,
993 obligations: &mut Vec<PredicateObligation<'tcx>>,
995 opt_normalize_projection_type(
1005 .unwrap_or_else(move || {
1006 // if we bottom out in ambiguity, create a type variable
1007 // and a deferred predicate to resolve this when more type
1008 // information is available.
1012 .infer_projection(param_env, projection_ty, cause, depth + 1, obligations)
1017 /// The guts of `normalize`: normalize a specific projection like `<T
1018 /// as Trait>::Item`. The result is always a type (and possibly
1019 /// additional obligations). Returns `None` in the case of ambiguity,
1020 /// which indicates that there are unbound type variables.
1022 /// This function used to return `Option<NormalizedTy<'tcx>>`, which contains a
1023 /// `Ty<'tcx>` and an obligations vector. But that obligation vector was very
1024 /// often immediately appended to another obligations vector. So now this
1025 /// function takes an obligations vector and appends to it directly, which is
1026 /// slightly uglier but avoids the need for an extra short-lived allocation.
1027 #[instrument(level = "debug", skip(selcx, param_env, cause, obligations))]
1028 fn opt_normalize_projection_type<'a, 'b, 'tcx>(
1029 selcx: &'a mut SelectionContext<'b, 'tcx>,
1030 param_env: ty::ParamEnv<'tcx>,
1031 projection_ty: ty::ProjectionTy<'tcx>,
1032 cause: ObligationCause<'tcx>,
1034 obligations: &mut Vec<PredicateObligation<'tcx>>,
1035 ) -> Result<Option<Term<'tcx>>, InProgress> {
1036 let infcx = selcx.infcx();
1037 // Don't use the projection cache in intercrate mode -
1038 // the `infcx` may be re-used between intercrate in non-intercrate
1039 // mode, which could lead to using incorrect cache results.
1040 let use_cache = !selcx.is_intercrate();
1042 let projection_ty = infcx.resolve_vars_if_possible(projection_ty);
1043 let cache_key = ProjectionCacheKey::new(projection_ty);
1045 // FIXME(#20304) For now, I am caching here, which is good, but it
1046 // means we don't capture the type variables that are created in
1047 // the case of ambiguity. Which means we may create a large stream
1048 // of such variables. OTOH, if we move the caching up a level, we
1049 // would not benefit from caching when proving `T: Trait<U=Foo>`
1050 // bounds. It might be the case that we want two distinct caches,
1051 // or else another kind of cache entry.
1053 let cache_result = if use_cache {
1054 infcx.inner.borrow_mut().projection_cache().try_start(cache_key)
1058 match cache_result {
1059 Ok(()) => debug!("no cache"),
1060 Err(ProjectionCacheEntry::Ambiguous) => {
1061 // If we found ambiguity the last time, that means we will continue
1062 // to do so until some type in the key changes (and we know it
1063 // hasn't, because we just fully resolved it).
1064 debug!("found cache entry: ambiguous");
1067 Err(ProjectionCacheEntry::InProgress) => {
1068 // Under lazy normalization, this can arise when
1069 // bootstrapping. That is, imagine an environment with a
1070 // where-clause like `A::B == u32`. Now, if we are asked
1071 // to normalize `A::B`, we will want to check the
1072 // where-clauses in scope. So we will try to unify `A::B`
1073 // with `A::B`, which can trigger a recursive
1076 debug!("found cache entry: in-progress");
1078 // Cache that normalizing this projection resulted in a cycle. This
1079 // should ensure that, unless this happens within a snapshot that's
1080 // rolled back, fulfillment or evaluation will notice the cycle.
1083 infcx.inner.borrow_mut().projection_cache().recur(cache_key);
1085 return Err(InProgress);
1087 Err(ProjectionCacheEntry::Recur) => {
1088 debug!("recur cache");
1089 return Err(InProgress);
1091 Err(ProjectionCacheEntry::NormalizedTy { ty, complete: _ }) => {
1092 // This is the hottest path in this function.
1094 // If we find the value in the cache, then return it along
1095 // with the obligations that went along with it. Note
1096 // that, when using a fulfillment context, these
1097 // obligations could in principle be ignored: they have
1098 // already been registered when the cache entry was
1099 // created (and hence the new ones will quickly be
1100 // discarded as duplicated). But when doing trait
1101 // evaluation this is not the case, and dropping the trait
1102 // evaluations can causes ICEs (e.g., #43132).
1103 debug!(?ty, "found normalized ty");
1104 obligations.extend(ty.obligations);
1105 return Ok(Some(ty.value));
1107 Err(ProjectionCacheEntry::Error) => {
1108 debug!("opt_normalize_projection_type: found error");
1109 let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth);
1110 obligations.extend(result.obligations);
1111 return Ok(Some(result.value.into()));
1116 Obligation::with_depth(selcx.tcx(), cause.clone(), depth, param_env, projection_ty);
1118 match project(selcx, &obligation) {
1119 Ok(Projected::Progress(Progress {
1120 term: projected_term,
1121 obligations: mut projected_obligations,
1123 // if projection succeeded, then what we get out of this
1124 // is also non-normalized (consider: it was derived from
1125 // an impl, where-clause etc) and hence we must
1128 let projected_term = selcx.infcx().resolve_vars_if_possible(projected_term);
1130 let mut result = if projected_term.has_projections() {
1131 let mut normalizer = AssocTypeNormalizer::new(
1136 &mut projected_obligations,
1138 let normalized_ty = normalizer.fold(projected_term);
1140 Normalized { value: normalized_ty, obligations: projected_obligations }
1142 Normalized { value: projected_term, obligations: projected_obligations }
1145 let mut deduped: SsoHashSet<_> = Default::default();
1146 result.obligations.drain_filter(|projected_obligation| {
1147 if !deduped.insert(projected_obligation.clone()) {
1154 infcx.inner.borrow_mut().projection_cache().insert_term(cache_key, result.clone());
1156 obligations.extend(result.obligations);
1157 Ok(Some(result.value))
1159 Ok(Projected::NoProgress(projected_ty)) => {
1160 let result = Normalized { value: projected_ty, obligations: vec![] };
1162 infcx.inner.borrow_mut().projection_cache().insert_term(cache_key, result.clone());
1164 // No need to extend `obligations`.
1165 Ok(Some(result.value))
1167 Err(ProjectionError::TooManyCandidates) => {
1168 debug!("opt_normalize_projection_type: too many candidates");
1170 infcx.inner.borrow_mut().projection_cache().ambiguous(cache_key);
1174 Err(ProjectionError::TraitSelectionError(_)) => {
1175 debug!("opt_normalize_projection_type: ERROR");
1176 // if we got an error processing the `T as Trait` part,
1177 // just return `ty::err` but add the obligation `T :
1178 // Trait`, which when processed will cause the error to be
1182 infcx.inner.borrow_mut().projection_cache().error(cache_key);
1184 let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth);
1185 obligations.extend(result.obligations);
1186 Ok(Some(result.value.into()))
1191 /// If we are projecting `<T as Trait>::Item`, but `T: Trait` does not
1192 /// hold. In various error cases, we cannot generate a valid
1193 /// normalized projection. Therefore, we create an inference variable
1194 /// return an associated obligation that, when fulfilled, will lead to
1197 /// Note that we used to return `Error` here, but that was quite
1198 /// dubious -- the premise was that an error would *eventually* be
1199 /// reported, when the obligation was processed. But in general once
1200 /// you see an `Error` you are supposed to be able to assume that an
1201 /// error *has been* reported, so that you can take whatever heuristic
1202 /// paths you want to take. To make things worse, it was possible for
1203 /// cycles to arise, where you basically had a setup like `<MyType<$0>
1204 /// as Trait>::Foo == $0`. Here, normalizing `<MyType<$0> as
1205 /// Trait>::Foo> to `[type error]` would lead to an obligation of
1206 /// `<MyType<[type error]> as Trait>::Foo`. We are supposed to report
1207 /// an error for this obligation, but we legitimately should not,
1208 /// because it contains `[type error]`. Yuck! (See issue #29857 for
1209 /// one case where this arose.)
1210 fn normalize_to_error<'a, 'tcx>(
1211 selcx: &mut SelectionContext<'a, 'tcx>,
1212 param_env: ty::ParamEnv<'tcx>,
1213 projection_ty: ty::ProjectionTy<'tcx>,
1214 cause: ObligationCause<'tcx>,
1216 ) -> NormalizedTy<'tcx> {
1217 let trait_ref = ty::Binder::dummy(projection_ty.trait_ref(selcx.tcx()));
1218 let trait_obligation = Obligation {
1220 recursion_depth: depth,
1222 predicate: trait_ref.without_const().to_predicate(selcx.tcx()),
1224 let tcx = selcx.infcx().tcx;
1225 let def_id = projection_ty.item_def_id;
1226 let new_value = selcx.infcx().next_ty_var(TypeVariableOrigin {
1227 kind: TypeVariableOriginKind::NormalizeProjectionType,
1228 span: tcx.def_span(def_id),
1230 Normalized { value: new_value, obligations: vec![trait_obligation] }
1233 enum Projected<'tcx> {
1234 Progress(Progress<'tcx>),
1235 NoProgress(ty::Term<'tcx>),
1238 struct Progress<'tcx> {
1239 term: ty::Term<'tcx>,
1240 obligations: Vec<PredicateObligation<'tcx>>,
1243 impl<'tcx> Progress<'tcx> {
1244 fn error(tcx: TyCtxt<'tcx>) -> Self {
1245 Progress { term: tcx.ty_error().into(), obligations: vec![] }
1248 fn with_addl_obligations(mut self, mut obligations: Vec<PredicateObligation<'tcx>>) -> Self {
1249 self.obligations.append(&mut obligations);
1254 /// Computes the result of a projection type (if we can).
1257 /// - `obligation` must be fully normalized
1258 #[instrument(level = "info", skip(selcx))]
1259 fn project<'cx, 'tcx>(
1260 selcx: &mut SelectionContext<'cx, 'tcx>,
1261 obligation: &ProjectionTyObligation<'tcx>,
1262 ) -> Result<Projected<'tcx>, ProjectionError<'tcx>> {
1263 if !selcx.tcx().recursion_limit().value_within_limit(obligation.recursion_depth) {
1264 // This should really be an immediate error, but some existing code
1265 // relies on being able to recover from this.
1266 return Err(ProjectionError::TraitSelectionError(SelectionError::Overflow(
1267 OverflowError::Canonical,
1271 if obligation.predicate.references_error() {
1272 return Ok(Projected::Progress(Progress::error(selcx.tcx())));
1275 let mut candidates = ProjectionCandidateSet::None;
1277 assemble_candidate_for_impl_trait_in_trait(selcx, obligation, &mut candidates);
1279 // Make sure that the following procedures are kept in order. ParamEnv
1280 // needs to be first because it has highest priority, and Select checks
1281 // the return value of push_candidate which assumes it's ran at last.
1282 assemble_candidates_from_param_env(selcx, obligation, &mut candidates);
1284 assemble_candidates_from_trait_def(selcx, obligation, &mut candidates);
1286 assemble_candidates_from_object_ty(selcx, obligation, &mut candidates);
1288 if let ProjectionCandidateSet::Single(ProjectionCandidate::Object(_)) = candidates {
1289 // Avoid normalization cycle from selection (see
1290 // `assemble_candidates_from_object_ty`).
1291 // FIXME(lazy_normalization): Lazy normalization should save us from
1292 // having to special case this.
1294 assemble_candidates_from_impls(selcx, obligation, &mut candidates);
1298 ProjectionCandidateSet::Single(candidate) => {
1299 Ok(Projected::Progress(confirm_candidate(selcx, obligation, candidate)))
1301 ProjectionCandidateSet::None => Ok(Projected::NoProgress(
1302 // FIXME(associated_const_generics): this may need to change in the future?
1303 // need to investigate whether or not this is fine.
1306 .mk_projection(obligation.predicate.item_def_id, obligation.predicate.substs)
1309 // Error occurred while trying to processing impls.
1310 ProjectionCandidateSet::Error(e) => Err(ProjectionError::TraitSelectionError(e)),
1311 // Inherent ambiguity that prevents us from even enumerating the
1313 ProjectionCandidateSet::Ambiguous => Err(ProjectionError::TooManyCandidates),
1317 /// If the predicate's item is an `ImplTraitPlaceholder`, we do a select on the
1318 /// corresponding trait ref. If this yields an `impl`, then we're able to project
1319 /// to a concrete type, since we have an `impl`'s method to provide the RPITIT.
1320 fn assemble_candidate_for_impl_trait_in_trait<'cx, 'tcx>(
1321 selcx: &mut SelectionContext<'cx, 'tcx>,
1322 obligation: &ProjectionTyObligation<'tcx>,
1323 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1325 let tcx = selcx.tcx();
1326 if tcx.def_kind(obligation.predicate.item_def_id) == DefKind::ImplTraitPlaceholder {
1327 let trait_fn_def_id = tcx.impl_trait_in_trait_parent(obligation.predicate.item_def_id);
1328 // If we are trying to project an RPITIT with trait's default `Self` parameter,
1329 // then we must be within a default trait body.
1330 if obligation.predicate.self_ty()
1331 == ty::InternalSubsts::identity_for_item(tcx, obligation.predicate.item_def_id)
1333 && tcx.associated_item(trait_fn_def_id).defaultness(tcx).has_value()
1335 candidate_set.push_candidate(ProjectionCandidate::ImplTraitInTrait(
1336 ImplTraitInTraitCandidate::Trait,
1341 let trait_def_id = tcx.parent(trait_fn_def_id);
1343 obligation.predicate.substs.truncate_to(tcx, tcx.generics_of(trait_def_id));
1344 // FIXME(named-returns): Binders
1345 let trait_predicate =
1346 ty::Binder::dummy(ty::TraitRef { def_id: trait_def_id, substs: trait_substs })
1347 .to_poly_trait_predicate();
1349 let _ = selcx.infcx().commit_if_ok(|_| {
1350 match selcx.select(&obligation.with(tcx, trait_predicate)) {
1351 Ok(Some(super::ImplSource::UserDefined(data))) => {
1352 candidate_set.push_candidate(ProjectionCandidate::ImplTraitInTrait(
1353 ImplTraitInTraitCandidate::Impl(data),
1358 candidate_set.mark_ambiguous();
1362 // Don't know enough about the impl to provide a useful signature
1366 debug!(error = ?e, "selection error");
1367 candidate_set.mark_error(e);
1375 /// The first thing we have to do is scan through the parameter
1376 /// environment to see whether there are any projection predicates
1377 /// there that can answer this question.
1378 fn assemble_candidates_from_param_env<'cx, 'tcx>(
1379 selcx: &mut SelectionContext<'cx, 'tcx>,
1380 obligation: &ProjectionTyObligation<'tcx>,
1381 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1383 assemble_candidates_from_predicates(
1387 ProjectionCandidate::ParamEnv,
1388 obligation.param_env.caller_bounds().iter(),
1393 /// In the case of a nested projection like `<<A as Foo>::FooT as Bar>::BarT`, we may find
1394 /// that the definition of `Foo` has some clues:
1396 /// ```ignore (illustrative)
1398 /// type FooT : Bar<BarT=i32>
1402 /// Here, for example, we could conclude that the result is `i32`.
1403 fn assemble_candidates_from_trait_def<'cx, 'tcx>(
1404 selcx: &mut SelectionContext<'cx, 'tcx>,
1405 obligation: &ProjectionTyObligation<'tcx>,
1406 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1408 debug!("assemble_candidates_from_trait_def(..)");
1410 let tcx = selcx.tcx();
1411 // Check whether the self-type is itself a projection.
1412 // If so, extract what we know from the trait and try to come up with a good answer.
1413 let bounds = match *obligation.predicate.self_ty().kind() {
1414 ty::Projection(ref data) => tcx.bound_item_bounds(data.item_def_id).subst(tcx, data.substs),
1415 ty::Opaque(def_id, substs) => tcx.bound_item_bounds(def_id).subst(tcx, substs),
1416 ty::Infer(ty::TyVar(_)) => {
1417 // If the self-type is an inference variable, then it MAY wind up
1418 // being a projected type, so induce an ambiguity.
1419 candidate_set.mark_ambiguous();
1425 assemble_candidates_from_predicates(
1429 ProjectionCandidate::TraitDef,
1435 /// In the case of a trait object like
1436 /// `<dyn Iterator<Item = ()> as Iterator>::Item` we can use the existential
1437 /// predicate in the trait object.
1439 /// We don't go through the select candidate for these bounds to avoid cycles:
1440 /// In the above case, `dyn Iterator<Item = ()>: Iterator` would create a
1441 /// nested obligation of `<dyn Iterator<Item = ()> as Iterator>::Item: Sized`,
1442 /// this then has to be normalized without having to prove
1443 /// `dyn Iterator<Item = ()>: Iterator` again.
1444 fn assemble_candidates_from_object_ty<'cx, 'tcx>(
1445 selcx: &mut SelectionContext<'cx, 'tcx>,
1446 obligation: &ProjectionTyObligation<'tcx>,
1447 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1449 debug!("assemble_candidates_from_object_ty(..)");
1451 let tcx = selcx.tcx();
1453 let self_ty = obligation.predicate.self_ty();
1454 let object_ty = selcx.infcx().shallow_resolve(self_ty);
1455 let data = match object_ty.kind() {
1456 ty::Dynamic(data, ..) => data,
1457 ty::Infer(ty::TyVar(_)) => {
1458 // If the self-type is an inference variable, then it MAY wind up
1459 // being an object type, so induce an ambiguity.
1460 candidate_set.mark_ambiguous();
1465 let env_predicates = data
1466 .projection_bounds()
1467 .filter(|bound| bound.item_def_id() == obligation.predicate.item_def_id)
1468 .map(|p| p.with_self_ty(tcx, object_ty).to_predicate(tcx));
1470 assemble_candidates_from_predicates(
1474 ProjectionCandidate::Object,
1482 skip(selcx, candidate_set, ctor, env_predicates, potentially_unnormalized_candidates)
1484 fn assemble_candidates_from_predicates<'cx, 'tcx>(
1485 selcx: &mut SelectionContext<'cx, 'tcx>,
1486 obligation: &ProjectionTyObligation<'tcx>,
1487 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1488 ctor: fn(ty::PolyProjectionPredicate<'tcx>) -> ProjectionCandidate<'tcx>,
1489 env_predicates: impl Iterator<Item = ty::Predicate<'tcx>>,
1490 potentially_unnormalized_candidates: bool,
1492 let infcx = selcx.infcx();
1493 for predicate in env_predicates {
1494 let bound_predicate = predicate.kind();
1495 if let ty::PredicateKind::Projection(data) = predicate.kind().skip_binder() {
1496 let data = bound_predicate.rebind(data);
1497 if data.projection_def_id() != obligation.predicate.item_def_id {
1501 let is_match = infcx.probe(|_| {
1502 selcx.match_projection_projections(
1505 potentially_unnormalized_candidates,
1510 ProjectionMatchesProjection::Yes => {
1511 candidate_set.push_candidate(ctor(data));
1513 if potentially_unnormalized_candidates
1514 && !obligation.predicate.has_non_region_infer()
1516 // HACK: Pick the first trait def candidate for a fully
1517 // inferred predicate. This is to allow duplicates that
1518 // differ only in normalization.
1522 ProjectionMatchesProjection::Ambiguous => {
1523 candidate_set.mark_ambiguous();
1525 ProjectionMatchesProjection::No => {}
1531 #[instrument(level = "debug", skip(selcx, obligation, candidate_set))]
1532 fn assemble_candidates_from_impls<'cx, 'tcx>(
1533 selcx: &mut SelectionContext<'cx, 'tcx>,
1534 obligation: &ProjectionTyObligation<'tcx>,
1535 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1537 // Can't assemble candidate from impl for RPITIT
1538 if selcx.tcx().def_kind(obligation.predicate.item_def_id) == DefKind::ImplTraitPlaceholder {
1542 // If we are resolving `<T as TraitRef<...>>::Item == Type`,
1543 // start out by selecting the predicate `T as TraitRef<...>`:
1544 let poly_trait_ref = ty::Binder::dummy(obligation.predicate.trait_ref(selcx.tcx()));
1545 let trait_obligation = obligation.with(selcx.tcx(), poly_trait_ref.to_poly_trait_predicate());
1546 let _ = selcx.infcx().commit_if_ok(|_| {
1547 let impl_source = match selcx.select(&trait_obligation) {
1548 Ok(Some(impl_source)) => impl_source,
1550 candidate_set.mark_ambiguous();
1554 debug!(error = ?e, "selection error");
1555 candidate_set.mark_error(e);
1560 let eligible = match &impl_source {
1561 super::ImplSource::Closure(_)
1562 | super::ImplSource::Generator(_)
1563 | super::ImplSource::FnPointer(_)
1564 | super::ImplSource::TraitAlias(_) => true,
1565 super::ImplSource::UserDefined(impl_data) => {
1566 // We have to be careful when projecting out of an
1567 // impl because of specialization. If we are not in
1568 // codegen (i.e., projection mode is not "any"), and the
1569 // impl's type is declared as default, then we disable
1570 // projection (even if the trait ref is fully
1571 // monomorphic). In the case where trait ref is not
1572 // fully monomorphic (i.e., includes type parameters),
1573 // this is because those type parameters may
1574 // ultimately be bound to types from other crates that
1575 // may have specialized impls we can't see. In the
1576 // case where the trait ref IS fully monomorphic, this
1577 // is a policy decision that we made in the RFC in
1578 // order to preserve flexibility for the crate that
1579 // defined the specializable impl to specialize later
1580 // for existing types.
1582 // In either case, we handle this by not adding a
1583 // candidate for an impl if it contains a `default`
1586 // NOTE: This should be kept in sync with the similar code in
1587 // `rustc_ty_utils::instance::resolve_associated_item()`.
1589 assoc_def(selcx, impl_data.impl_def_id, obligation.predicate.item_def_id)
1590 .map_err(|ErrorGuaranteed { .. }| ())?;
1592 if node_item.is_final() {
1593 // Non-specializable items are always projectable.
1596 // Only reveal a specializable default if we're past type-checking
1597 // and the obligation is monomorphic, otherwise passes such as
1598 // transmute checking and polymorphic MIR optimizations could
1599 // get a result which isn't correct for all monomorphizations.
1600 if obligation.param_env.reveal() == Reveal::All {
1601 // NOTE(eddyb) inference variables can resolve to parameters, so
1602 // assume `poly_trait_ref` isn't monomorphic, if it contains any.
1603 let poly_trait_ref = selcx.infcx().resolve_vars_if_possible(poly_trait_ref);
1604 !poly_trait_ref.still_further_specializable()
1607 assoc_ty = ?selcx.tcx().def_path_str(node_item.item.def_id),
1608 ?obligation.predicate,
1609 "assemble_candidates_from_impls: not eligible due to default",
1615 super::ImplSource::DiscriminantKind(..) => {
1616 // While `DiscriminantKind` is automatically implemented for every type,
1617 // the concrete discriminant may not be known yet.
1619 // Any type with multiple potential discriminant types is therefore not eligible.
1620 let self_ty = selcx.infcx().shallow_resolve(obligation.predicate.self_ty());
1622 match self_ty.kind() {
1640 | ty::GeneratorWitness(..)
1643 // Integers and floats always have `u8` as their discriminant.
1644 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(..)) => true,
1650 | ty::Placeholder(..)
1652 | ty::Error(_) => false,
1655 super::ImplSource::Pointee(..) => {
1656 // While `Pointee` is automatically implemented for every type,
1657 // the concrete metadata type may not be known yet.
1659 // Any type with multiple potential metadata types is therefore not eligible.
1660 let self_ty = selcx.infcx().shallow_resolve(obligation.predicate.self_ty());
1662 let tail = selcx.tcx().struct_tail_with_normalize(
1665 // We throw away any obligations we get from this, since we normalize
1666 // and confirm these obligations once again during confirmation
1667 normalize_with_depth(
1669 obligation.param_env,
1670 obligation.cause.clone(),
1671 obligation.recursion_depth + 1,
1695 | ty::GeneratorWitness(..)
1697 // Extern types have unit metadata, according to RFC 2850
1699 // If returned by `struct_tail_without_normalization` this is a unit struct
1700 // without any fields, or not a struct, and therefore is Sized.
1702 // If returned by `struct_tail_without_normalization` this is the empty tuple.
1704 // Integers and floats are always Sized, and so have unit type metadata.
1705 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(..)) => true,
1707 // type parameters, opaques, and unnormalized projections have pointer
1708 // metadata if they're known (e.g. by the param_env) to be sized
1709 ty::Param(_) | ty::Projection(..) | ty::Opaque(..)
1710 if selcx.infcx().predicate_must_hold_modulo_regions(
1713 ty::Binder::dummy(ty::TraitRef::new(
1714 selcx.tcx().require_lang_item(LangItem::Sized, None),
1715 selcx.tcx().mk_substs_trait(self_ty, &[]),
1724 // FIXME(compiler-errors): are Bound and Placeholder types ever known sized?
1726 | ty::Projection(..)
1729 | ty::Placeholder(..)
1732 if tail.has_infer_types() {
1733 candidate_set.mark_ambiguous();
1739 super::ImplSource::Param(..) => {
1740 // This case tell us nothing about the value of an
1741 // associated type. Consider:
1744 // trait SomeTrait { type Foo; }
1745 // fn foo<T:SomeTrait>(...) { }
1748 // If the user writes `<T as SomeTrait>::Foo`, then the `T
1749 // : SomeTrait` binding does not help us decide what the
1750 // type `Foo` is (at least, not more specifically than
1751 // what we already knew).
1753 // But wait, you say! What about an example like this:
1756 // fn bar<T:SomeTrait<Foo=usize>>(...) { ... }
1759 // Doesn't the `T : SomeTrait<Foo=usize>` predicate help
1760 // resolve `T::Foo`? And of course it does, but in fact
1761 // that single predicate is desugared into two predicates
1762 // in the compiler: a trait predicate (`T : SomeTrait`) and a
1763 // projection. And the projection where clause is handled
1764 // in `assemble_candidates_from_param_env`.
1767 super::ImplSource::Object(_) => {
1768 // Handled by the `Object` projection candidate. See
1769 // `assemble_candidates_from_object_ty` for an explanation of
1770 // why we special case object types.
1773 super::ImplSource::AutoImpl(..)
1774 | super::ImplSource::Builtin(..)
1775 | super::ImplSource::TraitUpcasting(_)
1776 | super::ImplSource::ConstDestruct(_) => {
1777 // These traits have no associated types.
1778 selcx.tcx().sess.delay_span_bug(
1779 obligation.cause.span,
1780 &format!("Cannot project an associated type from `{:?}`", impl_source),
1787 if candidate_set.push_candidate(ProjectionCandidate::Select(impl_source)) {
1798 fn confirm_candidate<'cx, 'tcx>(
1799 selcx: &mut SelectionContext<'cx, 'tcx>,
1800 obligation: &ProjectionTyObligation<'tcx>,
1801 candidate: ProjectionCandidate<'tcx>,
1802 ) -> Progress<'tcx> {
1803 debug!(?obligation, ?candidate, "confirm_candidate");
1804 let mut progress = match candidate {
1805 ProjectionCandidate::ParamEnv(poly_projection)
1806 | ProjectionCandidate::Object(poly_projection) => {
1807 confirm_param_env_candidate(selcx, obligation, poly_projection, false)
1810 ProjectionCandidate::TraitDef(poly_projection) => {
1811 confirm_param_env_candidate(selcx, obligation, poly_projection, true)
1814 ProjectionCandidate::Select(impl_source) => {
1815 confirm_select_candidate(selcx, obligation, impl_source)
1817 ProjectionCandidate::ImplTraitInTrait(ImplTraitInTraitCandidate::Impl(data)) => {
1818 confirm_impl_trait_in_trait_candidate(selcx, obligation, data)
1820 // If we're projecting an RPITIT for a default trait body, that's just
1821 // the same def-id, but as an opaque type (with regular RPIT semantics).
1822 ProjectionCandidate::ImplTraitInTrait(ImplTraitInTraitCandidate::Trait) => Progress {
1825 .mk_opaque(obligation.predicate.item_def_id, obligation.predicate.substs)
1827 obligations: vec![],
1831 // When checking for cycle during evaluation, we compare predicates with
1832 // "syntactic" equality. Since normalization generally introduces a type
1833 // with new region variables, we need to resolve them to existing variables
1834 // when possible for this to work. See `auto-trait-projection-recursion.rs`
1835 // for a case where this matters.
1836 if progress.term.has_infer_regions() {
1838 progress.term.fold_with(&mut OpportunisticRegionResolver::new(selcx.infcx()));
1843 fn confirm_select_candidate<'cx, 'tcx>(
1844 selcx: &mut SelectionContext<'cx, 'tcx>,
1845 obligation: &ProjectionTyObligation<'tcx>,
1846 impl_source: Selection<'tcx>,
1847 ) -> Progress<'tcx> {
1849 super::ImplSource::UserDefined(data) => confirm_impl_candidate(selcx, obligation, data),
1850 super::ImplSource::Generator(data) => confirm_generator_candidate(selcx, obligation, data),
1851 super::ImplSource::Closure(data) => confirm_closure_candidate(selcx, obligation, data),
1852 super::ImplSource::FnPointer(data) => confirm_fn_pointer_candidate(selcx, obligation, data),
1853 super::ImplSource::DiscriminantKind(data) => {
1854 confirm_discriminant_kind_candidate(selcx, obligation, data)
1856 super::ImplSource::Pointee(data) => confirm_pointee_candidate(selcx, obligation, data),
1857 super::ImplSource::Object(_)
1858 | super::ImplSource::AutoImpl(..)
1859 | super::ImplSource::Param(..)
1860 | super::ImplSource::Builtin(..)
1861 | super::ImplSource::TraitUpcasting(_)
1862 | super::ImplSource::TraitAlias(..)
1863 | super::ImplSource::ConstDestruct(_) => {
1864 // we don't create Select candidates with this kind of resolution
1866 obligation.cause.span,
1867 "Cannot project an associated type from `{:?}`",
1874 fn confirm_generator_candidate<'cx, 'tcx>(
1875 selcx: &mut SelectionContext<'cx, 'tcx>,
1876 obligation: &ProjectionTyObligation<'tcx>,
1877 impl_source: ImplSourceGeneratorData<'tcx, PredicateObligation<'tcx>>,
1878 ) -> Progress<'tcx> {
1879 let gen_sig = impl_source.substs.as_generator().poly_sig();
1880 let Normalized { value: gen_sig, obligations } = normalize_with_depth(
1882 obligation.param_env,
1883 obligation.cause.clone(),
1884 obligation.recursion_depth + 1,
1888 debug!(?obligation, ?gen_sig, ?obligations, "confirm_generator_candidate");
1890 let tcx = selcx.tcx();
1892 let gen_def_id = tcx.require_lang_item(LangItem::Generator, None);
1894 let predicate = super::util::generator_trait_ref_and_outputs(
1897 obligation.predicate.self_ty(),
1900 .map_bound(|(trait_ref, yield_ty, return_ty)| {
1901 let name = tcx.associated_item(obligation.predicate.item_def_id).name;
1902 let ty = if name == sym::Return {
1904 } else if name == sym::Yield {
1910 ty::ProjectionPredicate {
1911 projection_ty: ty::ProjectionTy {
1912 substs: trait_ref.substs,
1913 item_def_id: obligation.predicate.item_def_id,
1919 confirm_param_env_candidate(selcx, obligation, predicate, false)
1920 .with_addl_obligations(impl_source.nested)
1921 .with_addl_obligations(obligations)
1924 fn confirm_discriminant_kind_candidate<'cx, 'tcx>(
1925 selcx: &mut SelectionContext<'cx, 'tcx>,
1926 obligation: &ProjectionTyObligation<'tcx>,
1927 _: ImplSourceDiscriminantKindData,
1928 ) -> Progress<'tcx> {
1929 let tcx = selcx.tcx();
1931 let self_ty = selcx.infcx().shallow_resolve(obligation.predicate.self_ty());
1932 // We get here from `poly_project_and_unify_type` which replaces bound vars
1933 // with placeholders
1934 debug_assert!(!self_ty.has_escaping_bound_vars());
1935 let substs = tcx.mk_substs([self_ty.into()].iter());
1937 let discriminant_def_id = tcx.require_lang_item(LangItem::Discriminant, None);
1939 let predicate = ty::ProjectionPredicate {
1940 projection_ty: ty::ProjectionTy { substs, item_def_id: discriminant_def_id },
1941 term: self_ty.discriminant_ty(tcx).into(),
1944 // We get here from `poly_project_and_unify_type` which replaces bound vars
1945 // with placeholders, so dummy is okay here.
1946 confirm_param_env_candidate(selcx, obligation, ty::Binder::dummy(predicate), false)
1949 fn confirm_pointee_candidate<'cx, 'tcx>(
1950 selcx: &mut SelectionContext<'cx, 'tcx>,
1951 obligation: &ProjectionTyObligation<'tcx>,
1952 _: ImplSourcePointeeData,
1953 ) -> Progress<'tcx> {
1954 let tcx = selcx.tcx();
1955 let self_ty = selcx.infcx().shallow_resolve(obligation.predicate.self_ty());
1957 let mut obligations = vec![];
1958 let (metadata_ty, check_is_sized) = self_ty.ptr_metadata_ty(tcx, |ty| {
1959 normalize_with_depth_to(
1961 obligation.param_env,
1962 obligation.cause.clone(),
1963 obligation.recursion_depth + 1,
1969 let sized_predicate = ty::Binder::dummy(ty::TraitRef::new(
1970 tcx.require_lang_item(LangItem::Sized, None),
1971 tcx.mk_substs_trait(self_ty, &[]),
1974 obligations.push(obligation.with(tcx, sized_predicate));
1977 let substs = tcx.mk_substs([self_ty.into()].iter());
1978 let metadata_def_id = tcx.require_lang_item(LangItem::Metadata, None);
1980 let predicate = ty::ProjectionPredicate {
1981 projection_ty: ty::ProjectionTy { substs, item_def_id: metadata_def_id },
1982 term: metadata_ty.into(),
1985 confirm_param_env_candidate(selcx, obligation, ty::Binder::dummy(predicate), false)
1986 .with_addl_obligations(obligations)
1989 fn confirm_fn_pointer_candidate<'cx, 'tcx>(
1990 selcx: &mut SelectionContext<'cx, 'tcx>,
1991 obligation: &ProjectionTyObligation<'tcx>,
1992 fn_pointer_impl_source: ImplSourceFnPointerData<'tcx, PredicateObligation<'tcx>>,
1993 ) -> Progress<'tcx> {
1994 let fn_type = selcx.infcx().shallow_resolve(fn_pointer_impl_source.fn_ty);
1995 let sig = fn_type.fn_sig(selcx.tcx());
1996 let Normalized { value: sig, obligations } = normalize_with_depth(
1998 obligation.param_env,
1999 obligation.cause.clone(),
2000 obligation.recursion_depth + 1,
2004 confirm_callable_candidate(selcx, obligation, sig, util::TupleArgumentsFlag::Yes)
2005 .with_addl_obligations(fn_pointer_impl_source.nested)
2006 .with_addl_obligations(obligations)
2009 fn confirm_closure_candidate<'cx, 'tcx>(
2010 selcx: &mut SelectionContext<'cx, 'tcx>,
2011 obligation: &ProjectionTyObligation<'tcx>,
2012 impl_source: ImplSourceClosureData<'tcx, PredicateObligation<'tcx>>,
2013 ) -> Progress<'tcx> {
2014 let closure_sig = impl_source.substs.as_closure().sig();
2015 let Normalized { value: closure_sig, obligations } = normalize_with_depth(
2017 obligation.param_env,
2018 obligation.cause.clone(),
2019 obligation.recursion_depth + 1,
2023 debug!(?obligation, ?closure_sig, ?obligations, "confirm_closure_candidate");
2025 confirm_callable_candidate(selcx, obligation, closure_sig, util::TupleArgumentsFlag::No)
2026 .with_addl_obligations(impl_source.nested)
2027 .with_addl_obligations(obligations)
2030 fn confirm_callable_candidate<'cx, 'tcx>(
2031 selcx: &mut SelectionContext<'cx, 'tcx>,
2032 obligation: &ProjectionTyObligation<'tcx>,
2033 fn_sig: ty::PolyFnSig<'tcx>,
2034 flag: util::TupleArgumentsFlag,
2035 ) -> Progress<'tcx> {
2036 let tcx = selcx.tcx();
2038 debug!(?obligation, ?fn_sig, "confirm_callable_candidate");
2040 let fn_once_def_id = tcx.require_lang_item(LangItem::FnOnce, None);
2041 let fn_once_output_def_id = tcx.require_lang_item(LangItem::FnOnceOutput, None);
2043 let predicate = super::util::closure_trait_ref_and_return_type(
2046 obligation.predicate.self_ty(),
2050 .map_bound(|(trait_ref, ret_type)| ty::ProjectionPredicate {
2051 projection_ty: ty::ProjectionTy {
2052 substs: trait_ref.substs,
2053 item_def_id: fn_once_output_def_id,
2055 term: ret_type.into(),
2058 confirm_param_env_candidate(selcx, obligation, predicate, true)
2061 fn confirm_param_env_candidate<'cx, 'tcx>(
2062 selcx: &mut SelectionContext<'cx, 'tcx>,
2063 obligation: &ProjectionTyObligation<'tcx>,
2064 poly_cache_entry: ty::PolyProjectionPredicate<'tcx>,
2065 potentially_unnormalized_candidate: bool,
2066 ) -> Progress<'tcx> {
2067 let infcx = selcx.infcx();
2068 let cause = &obligation.cause;
2069 let param_env = obligation.param_env;
2071 let cache_entry = infcx.replace_bound_vars_with_fresh_vars(
2073 LateBoundRegionConversionTime::HigherRankedType,
2077 let cache_projection = cache_entry.projection_ty;
2078 let mut nested_obligations = Vec::new();
2079 let obligation_projection = obligation.predicate;
2080 let obligation_projection = ensure_sufficient_stack(|| {
2081 normalize_with_depth_to(
2083 obligation.param_env,
2084 obligation.cause.clone(),
2085 obligation.recursion_depth + 1,
2086 obligation_projection,
2087 &mut nested_obligations,
2090 let cache_projection = if potentially_unnormalized_candidate {
2091 ensure_sufficient_stack(|| {
2092 normalize_with_depth_to(
2094 obligation.param_env,
2095 obligation.cause.clone(),
2096 obligation.recursion_depth + 1,
2098 &mut nested_obligations,
2105 debug!(?cache_projection, ?obligation_projection);
2107 match infcx.at(cause, param_env).eq(cache_projection, obligation_projection) {
2108 Ok(InferOk { value: _, obligations }) => {
2109 nested_obligations.extend(obligations);
2110 assoc_ty_own_obligations(selcx, obligation, &mut nested_obligations);
2111 // FIXME(associated_const_equality): Handle consts here as well? Maybe this progress type should just take
2113 Progress { term: cache_entry.term, obligations: nested_obligations }
2117 "Failed to unify obligation `{:?}` with poly_projection `{:?}`: {:?}",
2118 obligation, poly_cache_entry, e,
2120 debug!("confirm_param_env_candidate: {}", msg);
2121 let err = infcx.tcx.ty_error_with_message(obligation.cause.span, &msg);
2122 Progress { term: err.into(), obligations: vec![] }
2127 fn confirm_impl_candidate<'cx, 'tcx>(
2128 selcx: &mut SelectionContext<'cx, 'tcx>,
2129 obligation: &ProjectionTyObligation<'tcx>,
2130 impl_impl_source: ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>>,
2131 ) -> Progress<'tcx> {
2132 let tcx = selcx.tcx();
2134 let ImplSourceUserDefinedData { impl_def_id, substs, mut nested } = impl_impl_source;
2135 let assoc_item_id = obligation.predicate.item_def_id;
2136 let trait_def_id = tcx.trait_id_of_impl(impl_def_id).unwrap();
2138 let param_env = obligation.param_env;
2139 let Ok(assoc_ty) = assoc_def(selcx, impl_def_id, assoc_item_id) else {
2140 return Progress { term: tcx.ty_error().into(), obligations: nested };
2143 if !assoc_ty.item.defaultness(tcx).has_value() {
2144 // This means that the impl is missing a definition for the
2145 // associated type. This error will be reported by the type
2146 // checker method `check_impl_items_against_trait`, so here we
2147 // just return Error.
2149 "confirm_impl_candidate: no associated type {:?} for {:?}",
2150 assoc_ty.item.name, obligation.predicate
2152 return Progress { term: tcx.ty_error().into(), obligations: nested };
2154 // If we're trying to normalize `<Vec<u32> as X>::A<S>` using
2155 //`impl<T> X for Vec<T> { type A<Y> = Box<Y>; }`, then:
2157 // * `obligation.predicate.substs` is `[Vec<u32>, S]`
2158 // * `substs` is `[u32]`
2159 // * `substs` ends up as `[u32, S]`
2160 let substs = obligation.predicate.substs.rebase_onto(tcx, trait_def_id, substs);
2162 translate_substs(selcx.infcx(), param_env, impl_def_id, substs, assoc_ty.defining_node);
2163 let ty = tcx.bound_type_of(assoc_ty.item.def_id);
2164 let is_const = matches!(tcx.def_kind(assoc_ty.item.def_id), DefKind::AssocConst);
2165 let term: ty::EarlyBinder<ty::Term<'tcx>> = if is_const {
2166 let identity_substs =
2167 crate::traits::InternalSubsts::identity_for_item(tcx, assoc_ty.item.def_id);
2168 let did = ty::WithOptConstParam::unknown(assoc_ty.item.def_id);
2169 let kind = ty::ConstKind::Unevaluated(ty::UnevaluatedConst::new(did, identity_substs));
2170 ty.map_bound(|ty| tcx.mk_const(kind, ty).into())
2172 ty.map_bound(|ty| ty.into())
2174 if !check_substs_compatible(tcx, &assoc_ty.item, substs) {
2175 let err = tcx.ty_error_with_message(
2176 obligation.cause.span,
2177 "impl item and trait item have different parameters",
2179 Progress { term: err.into(), obligations: nested }
2181 assoc_ty_own_obligations(selcx, obligation, &mut nested);
2182 Progress { term: term.subst(tcx, substs), obligations: nested }
2186 // Verify that the trait item and its implementation have compatible substs lists
2187 fn check_substs_compatible<'tcx>(
2189 assoc_item: &ty::AssocItem,
2190 substs: ty::SubstsRef<'tcx>,
2192 fn check_substs_compatible_inner<'tcx>(
2194 generics: &'tcx ty::Generics,
2195 args: &'tcx [ty::GenericArg<'tcx>],
2197 if generics.count() != args.len() {
2201 let (parent_args, own_args) = args.split_at(generics.parent_count);
2203 if let Some(parent) = generics.parent
2204 && let parent_generics = tcx.generics_of(parent)
2205 && !check_substs_compatible_inner(tcx, parent_generics, parent_args) {
2209 for (param, arg) in std::iter::zip(&generics.params, own_args) {
2210 match (¶m.kind, arg.unpack()) {
2211 (ty::GenericParamDefKind::Type { .. }, ty::GenericArgKind::Type(_))
2212 | (ty::GenericParamDefKind::Lifetime, ty::GenericArgKind::Lifetime(_))
2213 | (ty::GenericParamDefKind::Const { .. }, ty::GenericArgKind::Const(_)) => {}
2221 let generics = tcx.generics_of(assoc_item.def_id);
2222 // Chop off any additional substs (RPITIT) substs
2223 let substs = &substs[0..generics.count().min(substs.len())];
2224 check_substs_compatible_inner(tcx, generics, substs)
2227 fn confirm_impl_trait_in_trait_candidate<'tcx>(
2228 selcx: &mut SelectionContext<'_, 'tcx>,
2229 obligation: &ProjectionTyObligation<'tcx>,
2230 data: ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>>,
2231 ) -> Progress<'tcx> {
2232 let tcx = selcx.tcx();
2233 let mut obligations = data.nested;
2235 let trait_fn_def_id = tcx.impl_trait_in_trait_parent(obligation.predicate.item_def_id);
2236 let Ok(leaf_def) = assoc_def(selcx, data.impl_def_id, trait_fn_def_id) else {
2237 return Progress { term: tcx.ty_error().into(), obligations };
2239 if !leaf_def.item.defaultness(tcx).has_value() {
2240 return Progress { term: tcx.ty_error().into(), obligations };
2243 // Use the default `impl Trait` for the trait, e.g., for a default trait body
2244 if leaf_def.item.container == ty::AssocItemContainer::TraitContainer {
2247 .mk_opaque(obligation.predicate.item_def_id, obligation.predicate.substs)
2253 // Rebase from {trait}::{fn}::{opaque} to {impl}::{fn}::{opaque},
2254 // since `data.substs` are the impl substs.
2255 let impl_fn_substs =
2256 obligation.predicate.substs.rebase_onto(tcx, tcx.parent(trait_fn_def_id), data.substs);
2257 let impl_fn_substs = translate_substs(
2259 obligation.param_env,
2262 leaf_def.defining_node,
2265 if !check_substs_compatible(tcx, &leaf_def.item, impl_fn_substs) {
2266 let err = tcx.ty_error_with_message(
2267 obligation.cause.span,
2268 "impl method and trait method have different parameters",
2270 return Progress { term: err.into(), obligations };
2273 let impl_fn_def_id = leaf_def.item.def_id;
2275 let cause = ObligationCause::new(
2276 obligation.cause.span,
2277 obligation.cause.body_id,
2278 super::ItemObligation(impl_fn_def_id),
2280 let predicates = normalize_with_depth_to(
2282 obligation.param_env,
2284 obligation.recursion_depth + 1,
2285 tcx.predicates_of(impl_fn_def_id).instantiate(tcx, impl_fn_substs),
2288 obligations.extend(std::iter::zip(predicates.predicates, predicates.spans).map(
2290 Obligation::with_depth(
2292 ObligationCause::new(
2293 obligation.cause.span,
2294 obligation.cause.body_id,
2295 if span.is_dummy() {
2296 super::ItemObligation(impl_fn_def_id)
2298 super::BindingObligation(impl_fn_def_id, span)
2301 obligation.recursion_depth + 1,
2302 obligation.param_env,
2308 let ty = super::normalize_to(
2310 obligation.param_env,
2312 tcx.bound_trait_impl_trait_tys(impl_fn_def_id)
2314 tys.map_or_else(|_| tcx.ty_error(), |tys| tys[&obligation.predicate.item_def_id])
2316 .subst(tcx, impl_fn_substs),
2320 Progress { term: ty.into(), obligations }
2323 // Get obligations corresponding to the predicates from the where-clause of the
2324 // associated type itself.
2325 fn assoc_ty_own_obligations<'cx, 'tcx>(
2326 selcx: &mut SelectionContext<'cx, 'tcx>,
2327 obligation: &ProjectionTyObligation<'tcx>,
2328 nested: &mut Vec<PredicateObligation<'tcx>>,
2330 let tcx = selcx.tcx();
2331 for predicate in tcx
2332 .predicates_of(obligation.predicate.item_def_id)
2333 .instantiate_own(tcx, obligation.predicate.substs)
2336 let normalized = normalize_with_depth_to(
2338 obligation.param_env,
2339 obligation.cause.clone(),
2340 obligation.recursion_depth + 1,
2344 nested.push(Obligation::with_depth(
2346 obligation.cause.clone(),
2347 obligation.recursion_depth + 1,
2348 obligation.param_env,
2354 /// Locate the definition of an associated type in the specialization hierarchy,
2355 /// starting from the given impl.
2357 /// Based on the "projection mode", this lookup may in fact only examine the
2358 /// topmost impl. See the comments for `Reveal` for more details.
2360 selcx: &SelectionContext<'_, '_>,
2362 assoc_def_id: DefId,
2363 ) -> Result<specialization_graph::LeafDef, ErrorGuaranteed> {
2364 let tcx = selcx.tcx();
2365 let trait_def_id = tcx.impl_trait_ref(impl_def_id).unwrap().def_id;
2366 let trait_def = tcx.trait_def(trait_def_id);
2368 // This function may be called while we are still building the
2369 // specialization graph that is queried below (via TraitDef::ancestors()),
2370 // so, in order to avoid unnecessary infinite recursion, we manually look
2371 // for the associated item at the given impl.
2372 // If there is no such item in that impl, this function will fail with a
2373 // cycle error if the specialization graph is currently being built.
2374 if let Some(&impl_item_id) = tcx.impl_item_implementor_ids(impl_def_id).get(&assoc_def_id) {
2375 let item = tcx.associated_item(impl_item_id);
2376 let impl_node = specialization_graph::Node::Impl(impl_def_id);
2377 return Ok(specialization_graph::LeafDef {
2379 defining_node: impl_node,
2380 finalizing_node: if item.defaultness(tcx).is_default() {
2388 let ancestors = trait_def.ancestors(tcx, impl_def_id)?;
2389 if let Some(assoc_item) = ancestors.leaf_def(tcx, assoc_def_id) {
2392 // This is saying that neither the trait nor
2393 // the impl contain a definition for this
2394 // associated type. Normally this situation
2395 // could only arise through a compiler bug --
2396 // if the user wrote a bad item name, it
2397 // should have failed in astconv.
2399 "No associated type `{}` for {}",
2400 tcx.item_name(assoc_def_id),
2401 tcx.def_path_str(impl_def_id)
2406 pub(crate) trait ProjectionCacheKeyExt<'cx, 'tcx>: Sized {
2407 fn from_poly_projection_predicate(
2408 selcx: &mut SelectionContext<'cx, 'tcx>,
2409 predicate: ty::PolyProjectionPredicate<'tcx>,
2413 impl<'cx, 'tcx> ProjectionCacheKeyExt<'cx, 'tcx> for ProjectionCacheKey<'tcx> {
2414 fn from_poly_projection_predicate(
2415 selcx: &mut SelectionContext<'cx, 'tcx>,
2416 predicate: ty::PolyProjectionPredicate<'tcx>,
2418 let infcx = selcx.infcx();
2419 // We don't do cross-snapshot caching of obligations with escaping regions,
2420 // so there's no cache key to use
2421 predicate.no_bound_vars().map(|predicate| {
2422 ProjectionCacheKey::new(
2423 // We don't attempt to match up with a specific type-variable state
2424 // from a specific call to `opt_normalize_projection_type` - if
2425 // there's no precise match, the original cache entry is "stranded"
2427 infcx.resolve_vars_if_possible(predicate.projection_ty),