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(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 neccessary 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(
525 self.selcx.infcx().err_ctxt().report_overflow_error(&obligation, true);
528 let substs = substs.fold_with(self);
529 let generic_ty = self.tcx().bound_type_of(def_id);
530 let concrete_ty = generic_ty.subst(self.tcx(), substs);
532 let folded_ty = self.fold_ty(concrete_ty);
539 ty::Projection(data) if !data.has_escaping_bound_vars() => {
540 // This branch is *mostly* just an optimization: when we don't
541 // have escaping bound vars, we don't need to replace them with
542 // placeholders (see branch below). *Also*, we know that we can
543 // register an obligation to *later* project, since we know
544 // there won't be bound vars there.
545 let data = data.fold_with(self);
546 let normalized_ty = if self.eager_inference_replacement {
547 normalize_projection_type(
553 &mut self.obligations,
556 opt_normalize_projection_type(
562 &mut self.obligations,
566 .unwrap_or_else(|| ty.super_fold_with(self).into())
568 // For cases like #95134 we would like to catch overflows early
569 // otherwise they slip away and cause ICE.
570 let recursion_limit = self.tcx().recursion_limit();
571 if !recursion_limit.value_within_limit(self.depth)
572 // HACK: Don't overflow when running cargo doc see #100991
573 && !self.tcx().sess.opts.actually_rustdoc
575 let obligation = Obligation::with_depth(
581 self.selcx.infcx().err_ctxt().report_overflow_error(&obligation, true);
587 obligations.len = ?self.obligations.len(),
588 "AssocTypeNormalizer: normalized type"
590 normalized_ty.ty().unwrap()
593 ty::Projection(data) => {
594 // If there are escaping bound vars, we temporarily replace the
595 // bound vars with placeholders. Note though, that in the case
596 // that we still can't project for whatever reason (e.g. self
597 // type isn't known enough), we *can't* register an obligation
598 // and return an inference variable (since then that obligation
599 // would have bound vars and that's a can of worms). Instead,
600 // we just give up and fall back to pretending like we never tried!
602 // Note: this isn't necessarily the final approach here; we may
603 // want to figure out how to register obligations with escaping vars
604 // or handle this some other way.
606 let infcx = self.selcx.infcx();
607 let (data, mapped_regions, mapped_types, mapped_consts) =
608 BoundVarReplacer::replace_bound_vars(infcx, &mut self.universes, data);
609 let data = data.fold_with(self);
610 let normalized_ty = opt_normalize_projection_type(
616 &mut self.obligations,
620 .map(|term| term.ty().unwrap())
621 .map(|normalized_ty| {
622 PlaceholderReplacer::replace_placeholders(
631 .unwrap_or_else(|| ty.super_fold_with(self));
637 obligations.len = ?self.obligations.len(),
638 "AssocTypeNormalizer: normalized type"
643 _ => ty.super_fold_with(self),
647 #[instrument(skip(self), level = "debug")]
648 fn fold_const(&mut self, constant: ty::Const<'tcx>) -> ty::Const<'tcx> {
649 let tcx = self.selcx.tcx();
650 if tcx.lazy_normalization() {
653 let constant = constant.super_fold_with(self);
654 debug!(?constant, ?self.param_env);
655 with_replaced_escaping_bound_vars(
659 |constant| constant.eval(tcx, self.param_env),
665 fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
666 if p.allow_normalization() && needs_normalization(&p, self.param_env.reveal()) {
667 p.super_fold_with(self)
674 pub struct BoundVarReplacer<'me, 'tcx> {
675 infcx: &'me InferCtxt<'tcx>,
676 // These three maps track the bound variable that were replaced by placeholders. It might be
677 // nice to remove these since we already have the `kind` in the placeholder; we really just need
678 // the `var` (but we *could* bring that into scope if we were to track them as we pass them).
679 mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
680 mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy>,
681 mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
682 // The current depth relative to *this* folding, *not* the entire normalization. In other words,
683 // the depth of binders we've passed here.
684 current_index: ty::DebruijnIndex,
685 // The `UniverseIndex` of the binding levels above us. These are optional, since we are lazy:
686 // we don't actually create a universe until we see a bound var we have to replace.
687 universe_indices: &'me mut Vec<Option<ty::UniverseIndex>>,
690 /// Executes `f` on `value` after replacing all escaping bound variables with placeholders
691 /// and then replaces these placeholders with the original bound variables in the result.
693 /// In most places, bound variables should be replaced right when entering a binder, making
694 /// this function unnecessary. However, normalization currently does not do that, so we have
695 /// to do this lazily.
697 /// You should not add any additional uses of this function, at least not without first
698 /// discussing it with t-types.
700 /// FIXME(@lcnr): We may even consider experimenting with eagerly replacing bound vars during
701 /// normalization as well, at which point this function will be unnecessary and can be removed.
702 pub fn with_replaced_escaping_bound_vars<'a, 'tcx, T: TypeFoldable<'tcx>, R: TypeFoldable<'tcx>>(
703 infcx: &'a InferCtxt<'tcx>,
704 universe_indices: &'a mut Vec<Option<ty::UniverseIndex>>,
706 f: impl FnOnce(T) -> R,
708 if value.has_escaping_bound_vars() {
709 let (value, mapped_regions, mapped_types, mapped_consts) =
710 BoundVarReplacer::replace_bound_vars(infcx, universe_indices, value);
711 let result = f(value);
712 PlaceholderReplacer::replace_placeholders(
725 impl<'me, 'tcx> BoundVarReplacer<'me, 'tcx> {
726 /// Returns `Some` if we *were* able to replace bound vars. If there are any bound vars that
727 /// use a binding level above `universe_indices.len()`, we fail.
728 pub fn replace_bound_vars<T: TypeFoldable<'tcx>>(
729 infcx: &'me InferCtxt<'tcx>,
730 universe_indices: &'me mut Vec<Option<ty::UniverseIndex>>,
734 BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
735 BTreeMap<ty::PlaceholderType, ty::BoundTy>,
736 BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
738 let mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion> = BTreeMap::new();
739 let mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy> = BTreeMap::new();
740 let mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar> = BTreeMap::new();
742 let mut replacer = BoundVarReplacer {
747 current_index: ty::INNERMOST,
751 let value = value.fold_with(&mut replacer);
753 (value, replacer.mapped_regions, replacer.mapped_types, replacer.mapped_consts)
756 fn universe_for(&mut self, debruijn: ty::DebruijnIndex) -> ty::UniverseIndex {
757 let infcx = self.infcx;
759 self.universe_indices.len() + self.current_index.as_usize() - debruijn.as_usize() - 1;
760 let universe = self.universe_indices[index].unwrap_or_else(|| {
761 for i in self.universe_indices.iter_mut().take(index + 1) {
762 *i = i.or_else(|| Some(infcx.create_next_universe()))
764 self.universe_indices[index].unwrap()
770 impl<'tcx> TypeFolder<'tcx> for BoundVarReplacer<'_, 'tcx> {
771 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
775 fn fold_binder<T: TypeFoldable<'tcx>>(
777 t: ty::Binder<'tcx, T>,
778 ) -> ty::Binder<'tcx, T> {
779 self.current_index.shift_in(1);
780 let t = t.super_fold_with(self);
781 self.current_index.shift_out(1);
785 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
787 ty::ReLateBound(debruijn, _)
788 if debruijn.as_usize() + 1
789 > self.current_index.as_usize() + self.universe_indices.len() =>
791 bug!("Bound vars outside of `self.universe_indices`");
793 ty::ReLateBound(debruijn, br) if debruijn >= self.current_index => {
794 let universe = self.universe_for(debruijn);
795 let p = ty::PlaceholderRegion { universe, name: br.kind };
796 self.mapped_regions.insert(p, br);
797 self.infcx.tcx.mk_region(ty::RePlaceholder(p))
803 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
805 ty::Bound(debruijn, _)
806 if debruijn.as_usize() + 1
807 > self.current_index.as_usize() + self.universe_indices.len() =>
809 bug!("Bound vars outside of `self.universe_indices`");
811 ty::Bound(debruijn, bound_ty) if debruijn >= self.current_index => {
812 let universe = self.universe_for(debruijn);
813 let p = ty::PlaceholderType { universe, name: bound_ty.var };
814 self.mapped_types.insert(p, bound_ty);
815 self.infcx.tcx.mk_ty(ty::Placeholder(p))
817 _ if t.has_vars_bound_at_or_above(self.current_index) => t.super_fold_with(self),
822 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
824 ty::ConstKind::Bound(debruijn, _)
825 if debruijn.as_usize() + 1
826 > self.current_index.as_usize() + self.universe_indices.len() =>
828 bug!("Bound vars outside of `self.universe_indices`");
830 ty::ConstKind::Bound(debruijn, bound_const) if debruijn >= self.current_index => {
831 let universe = self.universe_for(debruijn);
832 let p = ty::PlaceholderConst { universe, name: bound_const };
833 self.mapped_consts.insert(p, bound_const);
836 .mk_const(ty::ConstS { kind: ty::ConstKind::Placeholder(p), ty: 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::ConstS {
972 kind: ty::ConstKind::Bound(db, *replace_var),
979 ct.super_fold_with(self)
984 /// The guts of `normalize`: normalize a specific projection like `<T
985 /// as Trait>::Item`. The result is always a type (and possibly
986 /// additional obligations). If ambiguity arises, which implies that
987 /// there are unresolved type variables in the projection, we will
988 /// substitute a fresh type variable `$X` and generate a new
989 /// obligation `<T as Trait>::Item == $X` for later.
990 pub fn normalize_projection_type<'a, 'b, 'tcx>(
991 selcx: &'a mut SelectionContext<'b, 'tcx>,
992 param_env: ty::ParamEnv<'tcx>,
993 projection_ty: ty::ProjectionTy<'tcx>,
994 cause: ObligationCause<'tcx>,
996 obligations: &mut Vec<PredicateObligation<'tcx>>,
998 opt_normalize_projection_type(
1008 .unwrap_or_else(move || {
1009 // if we bottom out in ambiguity, create a type variable
1010 // and a deferred predicate to resolve this when more type
1011 // information is available.
1015 .infer_projection(param_env, projection_ty, cause, depth + 1, obligations)
1020 /// The guts of `normalize`: normalize a specific projection like `<T
1021 /// as Trait>::Item`. The result is always a type (and possibly
1022 /// additional obligations). Returns `None` in the case of ambiguity,
1023 /// which indicates that there are unbound type variables.
1025 /// This function used to return `Option<NormalizedTy<'tcx>>`, which contains a
1026 /// `Ty<'tcx>` and an obligations vector. But that obligation vector was very
1027 /// often immediately appended to another obligations vector. So now this
1028 /// function takes an obligations vector and appends to it directly, which is
1029 /// slightly uglier but avoids the need for an extra short-lived allocation.
1030 #[instrument(level = "debug", skip(selcx, param_env, cause, obligations))]
1031 fn opt_normalize_projection_type<'a, 'b, 'tcx>(
1032 selcx: &'a mut SelectionContext<'b, 'tcx>,
1033 param_env: ty::ParamEnv<'tcx>,
1034 projection_ty: ty::ProjectionTy<'tcx>,
1035 cause: ObligationCause<'tcx>,
1037 obligations: &mut Vec<PredicateObligation<'tcx>>,
1038 ) -> Result<Option<Term<'tcx>>, InProgress> {
1039 let infcx = selcx.infcx();
1040 // Don't use the projection cache in intercrate mode -
1041 // the `infcx` may be re-used between intercrate in non-intercrate
1042 // mode, which could lead to using incorrect cache results.
1043 let use_cache = !selcx.is_intercrate();
1045 let projection_ty = infcx.resolve_vars_if_possible(projection_ty);
1046 let cache_key = ProjectionCacheKey::new(projection_ty);
1048 // FIXME(#20304) For now, I am caching here, which is good, but it
1049 // means we don't capture the type variables that are created in
1050 // the case of ambiguity. Which means we may create a large stream
1051 // of such variables. OTOH, if we move the caching up a level, we
1052 // would not benefit from caching when proving `T: Trait<U=Foo>`
1053 // bounds. It might be the case that we want two distinct caches,
1054 // or else another kind of cache entry.
1056 let cache_result = if use_cache {
1057 infcx.inner.borrow_mut().projection_cache().try_start(cache_key)
1061 match cache_result {
1062 Ok(()) => debug!("no cache"),
1063 Err(ProjectionCacheEntry::Ambiguous) => {
1064 // If we found ambiguity the last time, that means we will continue
1065 // to do so until some type in the key changes (and we know it
1066 // hasn't, because we just fully resolved it).
1067 debug!("found cache entry: ambiguous");
1070 Err(ProjectionCacheEntry::InProgress) => {
1071 // Under lazy normalization, this can arise when
1072 // bootstrapping. That is, imagine an environment with a
1073 // where-clause like `A::B == u32`. Now, if we are asked
1074 // to normalize `A::B`, we will want to check the
1075 // where-clauses in scope. So we will try to unify `A::B`
1076 // with `A::B`, which can trigger a recursive
1079 debug!("found cache entry: in-progress");
1081 // Cache that normalizing this projection resulted in a cycle. This
1082 // should ensure that, unless this happens within a snapshot that's
1083 // rolled back, fulfillment or evaluation will notice the cycle.
1086 infcx.inner.borrow_mut().projection_cache().recur(cache_key);
1088 return Err(InProgress);
1090 Err(ProjectionCacheEntry::Recur) => {
1091 debug!("recur cache");
1092 return Err(InProgress);
1094 Err(ProjectionCacheEntry::NormalizedTy { ty, complete: _ }) => {
1095 // This is the hottest path in this function.
1097 // If we find the value in the cache, then return it along
1098 // with the obligations that went along with it. Note
1099 // that, when using a fulfillment context, these
1100 // obligations could in principle be ignored: they have
1101 // already been registered when the cache entry was
1102 // created (and hence the new ones will quickly be
1103 // discarded as duplicated). But when doing trait
1104 // evaluation this is not the case, and dropping the trait
1105 // evaluations can causes ICEs (e.g., #43132).
1106 debug!(?ty, "found normalized ty");
1107 obligations.extend(ty.obligations);
1108 return Ok(Some(ty.value));
1110 Err(ProjectionCacheEntry::Error) => {
1111 debug!("opt_normalize_projection_type: found error");
1112 let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth);
1113 obligations.extend(result.obligations);
1114 return Ok(Some(result.value.into()));
1118 let obligation = Obligation::with_depth(cause.clone(), depth, param_env, projection_ty);
1120 match project(selcx, &obligation) {
1121 Ok(Projected::Progress(Progress {
1122 term: projected_term,
1123 obligations: mut projected_obligations,
1125 // if projection succeeded, then what we get out of this
1126 // is also non-normalized (consider: it was derived from
1127 // an impl, where-clause etc) and hence we must
1130 let projected_term = selcx.infcx().resolve_vars_if_possible(projected_term);
1132 let mut result = if projected_term.has_projections() {
1133 let mut normalizer = AssocTypeNormalizer::new(
1138 &mut projected_obligations,
1140 let normalized_ty = normalizer.fold(projected_term);
1142 Normalized { value: normalized_ty, obligations: projected_obligations }
1144 Normalized { value: projected_term, obligations: projected_obligations }
1147 let mut deduped: SsoHashSet<_> = Default::default();
1148 result.obligations.drain_filter(|projected_obligation| {
1149 if !deduped.insert(projected_obligation.clone()) {
1156 infcx.inner.borrow_mut().projection_cache().insert_term(cache_key, result.clone());
1158 obligations.extend(result.obligations);
1159 Ok(Some(result.value))
1161 Ok(Projected::NoProgress(projected_ty)) => {
1162 let result = Normalized { value: projected_ty, obligations: vec![] };
1164 infcx.inner.borrow_mut().projection_cache().insert_term(cache_key, result.clone());
1166 // No need to extend `obligations`.
1167 Ok(Some(result.value))
1169 Err(ProjectionError::TooManyCandidates) => {
1170 debug!("opt_normalize_projection_type: too many candidates");
1172 infcx.inner.borrow_mut().projection_cache().ambiguous(cache_key);
1176 Err(ProjectionError::TraitSelectionError(_)) => {
1177 debug!("opt_normalize_projection_type: ERROR");
1178 // if we got an error processing the `T as Trait` part,
1179 // just return `ty::err` but add the obligation `T :
1180 // Trait`, which when processed will cause the error to be
1184 infcx.inner.borrow_mut().projection_cache().error(cache_key);
1186 let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth);
1187 obligations.extend(result.obligations);
1188 Ok(Some(result.value.into()))
1193 /// If we are projecting `<T as Trait>::Item`, but `T: Trait` does not
1194 /// hold. In various error cases, we cannot generate a valid
1195 /// normalized projection. Therefore, we create an inference variable
1196 /// return an associated obligation that, when fulfilled, will lead to
1199 /// Note that we used to return `Error` here, but that was quite
1200 /// dubious -- the premise was that an error would *eventually* be
1201 /// reported, when the obligation was processed. But in general once
1202 /// you see an `Error` you are supposed to be able to assume that an
1203 /// error *has been* reported, so that you can take whatever heuristic
1204 /// paths you want to take. To make things worse, it was possible for
1205 /// cycles to arise, where you basically had a setup like `<MyType<$0>
1206 /// as Trait>::Foo == $0`. Here, normalizing `<MyType<$0> as
1207 /// Trait>::Foo> to `[type error]` would lead to an obligation of
1208 /// `<MyType<[type error]> as Trait>::Foo`. We are supposed to report
1209 /// an error for this obligation, but we legitimately should not,
1210 /// because it contains `[type error]`. Yuck! (See issue #29857 for
1211 /// one case where this arose.)
1212 fn normalize_to_error<'a, 'tcx>(
1213 selcx: &mut SelectionContext<'a, 'tcx>,
1214 param_env: ty::ParamEnv<'tcx>,
1215 projection_ty: ty::ProjectionTy<'tcx>,
1216 cause: ObligationCause<'tcx>,
1218 ) -> NormalizedTy<'tcx> {
1219 let trait_ref = ty::Binder::dummy(projection_ty.trait_ref(selcx.tcx()));
1220 let trait_obligation = Obligation {
1222 recursion_depth: depth,
1224 predicate: trait_ref.without_const().to_predicate(selcx.tcx()),
1226 let tcx = selcx.infcx().tcx;
1227 let def_id = projection_ty.item_def_id;
1228 let new_value = selcx.infcx().next_ty_var(TypeVariableOrigin {
1229 kind: TypeVariableOriginKind::NormalizeProjectionType,
1230 span: tcx.def_span(def_id),
1232 Normalized { value: new_value, obligations: vec![trait_obligation] }
1235 enum Projected<'tcx> {
1236 Progress(Progress<'tcx>),
1237 NoProgress(ty::Term<'tcx>),
1240 struct Progress<'tcx> {
1241 term: ty::Term<'tcx>,
1242 obligations: Vec<PredicateObligation<'tcx>>,
1245 impl<'tcx> Progress<'tcx> {
1246 fn error(tcx: TyCtxt<'tcx>) -> Self {
1247 Progress { term: tcx.ty_error().into(), obligations: vec![] }
1250 fn with_addl_obligations(mut self, mut obligations: Vec<PredicateObligation<'tcx>>) -> Self {
1251 self.obligations.append(&mut obligations);
1256 /// Computes the result of a projection type (if we can).
1259 /// - `obligation` must be fully normalized
1260 #[instrument(level = "info", skip(selcx))]
1261 fn project<'cx, 'tcx>(
1262 selcx: &mut SelectionContext<'cx, 'tcx>,
1263 obligation: &ProjectionTyObligation<'tcx>,
1264 ) -> Result<Projected<'tcx>, ProjectionError<'tcx>> {
1265 if !selcx.tcx().recursion_limit().value_within_limit(obligation.recursion_depth) {
1266 // This should really be an immediate error, but some existing code
1267 // relies on being able to recover from this.
1268 return Err(ProjectionError::TraitSelectionError(SelectionError::Overflow(
1269 OverflowError::Canonical,
1273 if obligation.predicate.references_error() {
1274 return Ok(Projected::Progress(Progress::error(selcx.tcx())));
1277 let mut candidates = ProjectionCandidateSet::None;
1279 assemble_candidate_for_impl_trait_in_trait(selcx, obligation, &mut candidates);
1281 // Make sure that the following procedures are kept in order. ParamEnv
1282 // needs to be first because it has highest priority, and Select checks
1283 // the return value of push_candidate which assumes it's ran at last.
1284 assemble_candidates_from_param_env(selcx, obligation, &mut candidates);
1286 assemble_candidates_from_trait_def(selcx, obligation, &mut candidates);
1288 assemble_candidates_from_object_ty(selcx, obligation, &mut candidates);
1290 if let ProjectionCandidateSet::Single(ProjectionCandidate::Object(_)) = candidates {
1291 // Avoid normalization cycle from selection (see
1292 // `assemble_candidates_from_object_ty`).
1293 // FIXME(lazy_normalization): Lazy normalization should save us from
1294 // having to special case this.
1296 assemble_candidates_from_impls(selcx, obligation, &mut candidates);
1300 ProjectionCandidateSet::Single(candidate) => {
1301 Ok(Projected::Progress(confirm_candidate(selcx, obligation, candidate)))
1303 ProjectionCandidateSet::None => Ok(Projected::NoProgress(
1304 // FIXME(associated_const_generics): this may need to change in the future?
1305 // need to investigate whether or not this is fine.
1308 .mk_projection(obligation.predicate.item_def_id, obligation.predicate.substs)
1311 // Error occurred while trying to processing impls.
1312 ProjectionCandidateSet::Error(e) => Err(ProjectionError::TraitSelectionError(e)),
1313 // Inherent ambiguity that prevents us from even enumerating the
1315 ProjectionCandidateSet::Ambiguous => Err(ProjectionError::TooManyCandidates),
1319 /// If the predicate's item is an `ImplTraitPlaceholder`, we do a select on the
1320 /// corresponding trait ref. If this yields an `impl`, then we're able to project
1321 /// to a concrete type, since we have an `impl`'s method to provide the RPITIT.
1322 fn assemble_candidate_for_impl_trait_in_trait<'cx, 'tcx>(
1323 selcx: &mut SelectionContext<'cx, 'tcx>,
1324 obligation: &ProjectionTyObligation<'tcx>,
1325 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1327 let tcx = selcx.tcx();
1328 if tcx.def_kind(obligation.predicate.item_def_id) == DefKind::ImplTraitPlaceholder {
1329 let trait_fn_def_id = tcx.impl_trait_in_trait_parent(obligation.predicate.item_def_id);
1330 // If we are trying to project an RPITIT with trait's default `Self` parameter,
1331 // then we must be within a default trait body.
1332 if obligation.predicate.self_ty()
1333 == ty::InternalSubsts::identity_for_item(tcx, obligation.predicate.item_def_id)
1335 && tcx.associated_item(trait_fn_def_id).defaultness(tcx).has_value()
1337 candidate_set.push_candidate(ProjectionCandidate::ImplTraitInTrait(
1338 ImplTraitInTraitCandidate::Trait,
1343 let trait_def_id = tcx.parent(trait_fn_def_id);
1345 obligation.predicate.substs.truncate_to(tcx, tcx.generics_of(trait_def_id));
1346 // FIXME(named-returns): Binders
1347 let trait_predicate =
1348 ty::Binder::dummy(ty::TraitRef { def_id: trait_def_id, substs: trait_substs })
1349 .to_poly_trait_predicate();
1352 selcx.infcx().commit_if_ok(|_| match selcx.select(&obligation.with(trait_predicate)) {
1353 Ok(Some(super::ImplSource::UserDefined(data))) => {
1354 candidate_set.push_candidate(ProjectionCandidate::ImplTraitInTrait(
1355 ImplTraitInTraitCandidate::Impl(data),
1360 candidate_set.mark_ambiguous();
1364 // Don't know enough about the impl to provide a useful signature
1368 debug!(error = ?e, "selection error");
1369 candidate_set.mark_error(e);
1376 /// The first thing we have to do is scan through the parameter
1377 /// environment to see whether there are any projection predicates
1378 /// there that can answer this question.
1379 fn assemble_candidates_from_param_env<'cx, 'tcx>(
1380 selcx: &mut SelectionContext<'cx, 'tcx>,
1381 obligation: &ProjectionTyObligation<'tcx>,
1382 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1384 assemble_candidates_from_predicates(
1388 ProjectionCandidate::ParamEnv,
1389 obligation.param_env.caller_bounds().iter(),
1394 /// In the case of a nested projection like `<<A as Foo>::FooT as Bar>::BarT`, we may find
1395 /// that the definition of `Foo` has some clues:
1397 /// ```ignore (illustrative)
1399 /// type FooT : Bar<BarT=i32>
1403 /// Here, for example, we could conclude that the result is `i32`.
1404 fn assemble_candidates_from_trait_def<'cx, 'tcx>(
1405 selcx: &mut SelectionContext<'cx, 'tcx>,
1406 obligation: &ProjectionTyObligation<'tcx>,
1407 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1409 debug!("assemble_candidates_from_trait_def(..)");
1411 let tcx = selcx.tcx();
1412 // Check whether the self-type is itself a projection.
1413 // If so, extract what we know from the trait and try to come up with a good answer.
1414 let bounds = match *obligation.predicate.self_ty().kind() {
1415 ty::Projection(ref data) => tcx.bound_item_bounds(data.item_def_id).subst(tcx, data.substs),
1416 ty::Opaque(def_id, substs) => tcx.bound_item_bounds(def_id).subst(tcx, substs),
1417 ty::Infer(ty::TyVar(_)) => {
1418 // If the self-type is an inference variable, then it MAY wind up
1419 // being a projected type, so induce an ambiguity.
1420 candidate_set.mark_ambiguous();
1426 assemble_candidates_from_predicates(
1430 ProjectionCandidate::TraitDef,
1436 /// In the case of a trait object like
1437 /// `<dyn Iterator<Item = ()> as Iterator>::Item` we can use the existential
1438 /// predicate in the trait object.
1440 /// We don't go through the select candidate for these bounds to avoid cycles:
1441 /// In the above case, `dyn Iterator<Item = ()>: Iterator` would create a
1442 /// nested obligation of `<dyn Iterator<Item = ()> as Iterator>::Item: Sized`,
1443 /// this then has to be normalized without having to prove
1444 /// `dyn Iterator<Item = ()>: Iterator` again.
1445 fn assemble_candidates_from_object_ty<'cx, 'tcx>(
1446 selcx: &mut SelectionContext<'cx, 'tcx>,
1447 obligation: &ProjectionTyObligation<'tcx>,
1448 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1450 debug!("assemble_candidates_from_object_ty(..)");
1452 let tcx = selcx.tcx();
1454 let self_ty = obligation.predicate.self_ty();
1455 let object_ty = selcx.infcx().shallow_resolve(self_ty);
1456 let data = match object_ty.kind() {
1457 ty::Dynamic(data, ..) => data,
1458 ty::Infer(ty::TyVar(_)) => {
1459 // If the self-type is an inference variable, then it MAY wind up
1460 // being an object type, so induce an ambiguity.
1461 candidate_set.mark_ambiguous();
1466 let env_predicates = data
1467 .projection_bounds()
1468 .filter(|bound| bound.item_def_id() == obligation.predicate.item_def_id)
1469 .map(|p| p.with_self_ty(tcx, object_ty).to_predicate(tcx));
1471 assemble_candidates_from_predicates(
1475 ProjectionCandidate::Object,
1483 skip(selcx, candidate_set, ctor, env_predicates, potentially_unnormalized_candidates)
1485 fn assemble_candidates_from_predicates<'cx, 'tcx>(
1486 selcx: &mut SelectionContext<'cx, 'tcx>,
1487 obligation: &ProjectionTyObligation<'tcx>,
1488 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1489 ctor: fn(ty::PolyProjectionPredicate<'tcx>) -> ProjectionCandidate<'tcx>,
1490 env_predicates: impl Iterator<Item = ty::Predicate<'tcx>>,
1491 potentially_unnormalized_candidates: bool,
1493 let infcx = selcx.infcx();
1494 for predicate in env_predicates {
1495 let bound_predicate = predicate.kind();
1496 if let ty::PredicateKind::Projection(data) = predicate.kind().skip_binder() {
1497 let data = bound_predicate.rebind(data);
1498 if data.projection_def_id() != obligation.predicate.item_def_id {
1502 let is_match = infcx.probe(|_| {
1503 selcx.match_projection_projections(
1506 potentially_unnormalized_candidates,
1511 ProjectionMatchesProjection::Yes => {
1512 candidate_set.push_candidate(ctor(data));
1514 if potentially_unnormalized_candidates
1515 && !obligation.predicate.has_non_region_infer()
1517 // HACK: Pick the first trait def candidate for a fully
1518 // inferred predicate. This is to allow duplicates that
1519 // differ only in normalization.
1523 ProjectionMatchesProjection::Ambiguous => {
1524 candidate_set.mark_ambiguous();
1526 ProjectionMatchesProjection::No => {}
1532 #[instrument(level = "debug", skip(selcx, obligation, candidate_set))]
1533 fn assemble_candidates_from_impls<'cx, 'tcx>(
1534 selcx: &mut SelectionContext<'cx, 'tcx>,
1535 obligation: &ProjectionTyObligation<'tcx>,
1536 candidate_set: &mut ProjectionCandidateSet<'tcx>,
1538 // Can't assemble candidate from impl for RPITIT
1539 if selcx.tcx().def_kind(obligation.predicate.item_def_id) == DefKind::ImplTraitPlaceholder {
1543 // If we are resolving `<T as TraitRef<...>>::Item == Type`,
1544 // start out by selecting the predicate `T as TraitRef<...>`:
1545 let poly_trait_ref = ty::Binder::dummy(obligation.predicate.trait_ref(selcx.tcx()));
1546 let trait_obligation = obligation.with(poly_trait_ref.to_poly_trait_predicate());
1547 let _ = selcx.infcx().commit_if_ok(|_| {
1548 let impl_source = match selcx.select(&trait_obligation) {
1549 Ok(Some(impl_source)) => impl_source,
1551 candidate_set.mark_ambiguous();
1555 debug!(error = ?e, "selection error");
1556 candidate_set.mark_error(e);
1561 let eligible = match &impl_source {
1562 super::ImplSource::Closure(_)
1563 | super::ImplSource::Generator(_)
1564 | super::ImplSource::FnPointer(_)
1565 | super::ImplSource::TraitAlias(_) => true,
1566 super::ImplSource::UserDefined(impl_data) => {
1567 // We have to be careful when projecting out of an
1568 // impl because of specialization. If we are not in
1569 // codegen (i.e., projection mode is not "any"), and the
1570 // impl's type is declared as default, then we disable
1571 // projection (even if the trait ref is fully
1572 // monomorphic). In the case where trait ref is not
1573 // fully monomorphic (i.e., includes type parameters),
1574 // this is because those type parameters may
1575 // ultimately be bound to types from other crates that
1576 // may have specialized impls we can't see. In the
1577 // case where the trait ref IS fully monomorphic, this
1578 // is a policy decision that we made in the RFC in
1579 // order to preserve flexibility for the crate that
1580 // defined the specializable impl to specialize later
1581 // for existing types.
1583 // In either case, we handle this by not adding a
1584 // candidate for an impl if it contains a `default`
1587 // NOTE: This should be kept in sync with the similar code in
1588 // `rustc_ty_utils::instance::resolve_associated_item()`.
1590 assoc_def(selcx, impl_data.impl_def_id, obligation.predicate.item_def_id)
1591 .map_err(|ErrorGuaranteed { .. }| ())?;
1593 if node_item.is_final() {
1594 // Non-specializable items are always projectable.
1597 // Only reveal a specializable default if we're past type-checking
1598 // and the obligation is monomorphic, otherwise passes such as
1599 // transmute checking and polymorphic MIR optimizations could
1600 // get a result which isn't correct for all monomorphizations.
1601 if obligation.param_env.reveal() == Reveal::All {
1602 // NOTE(eddyb) inference variables can resolve to parameters, so
1603 // assume `poly_trait_ref` isn't monomorphic, if it contains any.
1604 let poly_trait_ref = selcx.infcx().resolve_vars_if_possible(poly_trait_ref);
1605 !poly_trait_ref.still_further_specializable()
1608 assoc_ty = ?selcx.tcx().def_path_str(node_item.item.def_id),
1609 ?obligation.predicate,
1610 "assemble_candidates_from_impls: not eligible due to default",
1616 super::ImplSource::DiscriminantKind(..) => {
1617 // While `DiscriminantKind` is automatically implemented for every type,
1618 // the concrete discriminant may not be known yet.
1620 // Any type with multiple potential discriminant types is therefore not eligible.
1621 let self_ty = selcx.infcx().shallow_resolve(obligation.predicate.self_ty());
1623 match self_ty.kind() {
1641 | ty::GeneratorWitness(..)
1644 // Integers and floats always have `u8` as their discriminant.
1645 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(..)) => true,
1651 | ty::Placeholder(..)
1653 | ty::Error(_) => false,
1656 super::ImplSource::Pointee(..) => {
1657 // While `Pointee` is automatically implemented for every type,
1658 // the concrete metadata type may not be known yet.
1660 // Any type with multiple potential metadata types is therefore not eligible.
1661 let self_ty = selcx.infcx().shallow_resolve(obligation.predicate.self_ty());
1663 let tail = selcx.tcx().struct_tail_with_normalize(
1666 // We throw away any obligations we get from this, since we normalize
1667 // and confirm these obligations once again during confirmation
1668 normalize_with_depth(
1670 obligation.param_env,
1671 obligation.cause.clone(),
1672 obligation.recursion_depth + 1,
1696 | ty::GeneratorWitness(..)
1698 // Extern types have unit metadata, according to RFC 2850
1700 // If returned by `struct_tail_without_normalization` this is a unit struct
1701 // without any fields, or not a struct, and therefore is Sized.
1703 // If returned by `struct_tail_without_normalization` this is the empty tuple.
1705 // Integers and floats are always Sized, and so have unit type metadata.
1706 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(..)) => true,
1708 // type parameters, opaques, and unnormalized projections have pointer
1709 // metadata if they're known (e.g. by the param_env) to be sized
1710 ty::Param(_) | ty::Projection(..) | ty::Opaque(..)
1711 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, &[]),
1718 .to_predicate(selcx.tcx()),
1725 // FIXME(compiler-errors): are Bound and Placeholder types ever known sized?
1727 | ty::Projection(..)
1730 | ty::Placeholder(..)
1733 if tail.has_infer_types() {
1734 candidate_set.mark_ambiguous();
1740 super::ImplSource::Param(..) => {
1741 // This case tell us nothing about the value of an
1742 // associated type. Consider:
1745 // trait SomeTrait { type Foo; }
1746 // fn foo<T:SomeTrait>(...) { }
1749 // If the user writes `<T as SomeTrait>::Foo`, then the `T
1750 // : SomeTrait` binding does not help us decide what the
1751 // type `Foo` is (at least, not more specifically than
1752 // what we already knew).
1754 // But wait, you say! What about an example like this:
1757 // fn bar<T:SomeTrait<Foo=usize>>(...) { ... }
1760 // Doesn't the `T : SomeTrait<Foo=usize>` predicate help
1761 // resolve `T::Foo`? And of course it does, but in fact
1762 // that single predicate is desugared into two predicates
1763 // in the compiler: a trait predicate (`T : SomeTrait`) and a
1764 // projection. And the projection where clause is handled
1765 // in `assemble_candidates_from_param_env`.
1768 super::ImplSource::Object(_) => {
1769 // Handled by the `Object` projection candidate. See
1770 // `assemble_candidates_from_object_ty` for an explanation of
1771 // why we special case object types.
1774 super::ImplSource::AutoImpl(..)
1775 | super::ImplSource::Builtin(..)
1776 | super::ImplSource::TraitUpcasting(_)
1777 | super::ImplSource::ConstDestruct(_) => {
1778 // These traits have no associated types.
1779 selcx.tcx().sess.delay_span_bug(
1780 obligation.cause.span,
1781 &format!("Cannot project an associated type from `{:?}`", impl_source),
1788 if candidate_set.push_candidate(ProjectionCandidate::Select(impl_source)) {
1799 fn confirm_candidate<'cx, 'tcx>(
1800 selcx: &mut SelectionContext<'cx, 'tcx>,
1801 obligation: &ProjectionTyObligation<'tcx>,
1802 candidate: ProjectionCandidate<'tcx>,
1803 ) -> Progress<'tcx> {
1804 debug!(?obligation, ?candidate, "confirm_candidate");
1805 let mut progress = match candidate {
1806 ProjectionCandidate::ParamEnv(poly_projection)
1807 | ProjectionCandidate::Object(poly_projection) => {
1808 confirm_param_env_candidate(selcx, obligation, poly_projection, false)
1811 ProjectionCandidate::TraitDef(poly_projection) => {
1812 confirm_param_env_candidate(selcx, obligation, poly_projection, true)
1815 ProjectionCandidate::Select(impl_source) => {
1816 confirm_select_candidate(selcx, obligation, impl_source)
1818 ProjectionCandidate::ImplTraitInTrait(ImplTraitInTraitCandidate::Impl(data)) => {
1819 confirm_impl_trait_in_trait_candidate(selcx, obligation, data)
1821 // If we're projecting an RPITIT for a default trait body, that's just
1822 // the same def-id, but as an opaque type (with regular RPIT semantics).
1823 ProjectionCandidate::ImplTraitInTrait(ImplTraitInTraitCandidate::Trait) => Progress {
1826 .mk_opaque(obligation.predicate.item_def_id, obligation.predicate.substs)
1828 obligations: vec![],
1832 // When checking for cycle during evaluation, we compare predicates with
1833 // "syntactic" equality. Since normalization generally introduces a type
1834 // with new region variables, we need to resolve them to existing variables
1835 // when possible for this to work. See `auto-trait-projection-recursion.rs`
1836 // for a case where this matters.
1837 if progress.term.has_infer_regions() {
1839 progress.term.fold_with(&mut OpportunisticRegionResolver::new(selcx.infcx()));
1844 fn confirm_select_candidate<'cx, 'tcx>(
1845 selcx: &mut SelectionContext<'cx, 'tcx>,
1846 obligation: &ProjectionTyObligation<'tcx>,
1847 impl_source: Selection<'tcx>,
1848 ) -> Progress<'tcx> {
1850 super::ImplSource::UserDefined(data) => confirm_impl_candidate(selcx, obligation, data),
1851 super::ImplSource::Generator(data) => confirm_generator_candidate(selcx, obligation, data),
1852 super::ImplSource::Closure(data) => confirm_closure_candidate(selcx, obligation, data),
1853 super::ImplSource::FnPointer(data) => confirm_fn_pointer_candidate(selcx, obligation, data),
1854 super::ImplSource::DiscriminantKind(data) => {
1855 confirm_discriminant_kind_candidate(selcx, obligation, data)
1857 super::ImplSource::Pointee(data) => confirm_pointee_candidate(selcx, obligation, data),
1858 super::ImplSource::Object(_)
1859 | super::ImplSource::AutoImpl(..)
1860 | super::ImplSource::Param(..)
1861 | super::ImplSource::Builtin(..)
1862 | super::ImplSource::TraitUpcasting(_)
1863 | super::ImplSource::TraitAlias(..)
1864 | super::ImplSource::ConstDestruct(_) => {
1865 // we don't create Select candidates with this kind of resolution
1867 obligation.cause.span,
1868 "Cannot project an associated type from `{:?}`",
1875 fn confirm_generator_candidate<'cx, 'tcx>(
1876 selcx: &mut SelectionContext<'cx, 'tcx>,
1877 obligation: &ProjectionTyObligation<'tcx>,
1878 impl_source: ImplSourceGeneratorData<'tcx, PredicateObligation<'tcx>>,
1879 ) -> Progress<'tcx> {
1880 let gen_sig = impl_source.substs.as_generator().poly_sig();
1881 let Normalized { value: gen_sig, obligations } = normalize_with_depth(
1883 obligation.param_env,
1884 obligation.cause.clone(),
1885 obligation.recursion_depth + 1,
1889 debug!(?obligation, ?gen_sig, ?obligations, "confirm_generator_candidate");
1891 let tcx = selcx.tcx();
1893 let gen_def_id = tcx.require_lang_item(LangItem::Generator, None);
1895 let predicate = super::util::generator_trait_ref_and_outputs(
1898 obligation.predicate.self_ty(),
1901 .map_bound(|(trait_ref, yield_ty, return_ty)| {
1902 let name = tcx.associated_item(obligation.predicate.item_def_id).name;
1903 let ty = if name == sym::Return {
1905 } else if name == sym::Yield {
1911 ty::ProjectionPredicate {
1912 projection_ty: ty::ProjectionTy {
1913 substs: trait_ref.substs,
1914 item_def_id: obligation.predicate.item_def_id,
1920 confirm_param_env_candidate(selcx, obligation, predicate, false)
1921 .with_addl_obligations(impl_source.nested)
1922 .with_addl_obligations(obligations)
1925 fn confirm_discriminant_kind_candidate<'cx, 'tcx>(
1926 selcx: &mut SelectionContext<'cx, 'tcx>,
1927 obligation: &ProjectionTyObligation<'tcx>,
1928 _: ImplSourceDiscriminantKindData,
1929 ) -> Progress<'tcx> {
1930 let tcx = selcx.tcx();
1932 let self_ty = selcx.infcx().shallow_resolve(obligation.predicate.self_ty());
1933 // We get here from `poly_project_and_unify_type` which replaces bound vars
1934 // with placeholders
1935 debug_assert!(!self_ty.has_escaping_bound_vars());
1936 let substs = tcx.mk_substs([self_ty.into()].iter());
1938 let discriminant_def_id = tcx.require_lang_item(LangItem::Discriminant, None);
1940 let predicate = ty::ProjectionPredicate {
1941 projection_ty: ty::ProjectionTy { substs, item_def_id: discriminant_def_id },
1942 term: self_ty.discriminant_ty(tcx).into(),
1945 // We get here from `poly_project_and_unify_type` which replaces bound vars
1946 // with placeholders, so dummy is okay here.
1947 confirm_param_env_candidate(selcx, obligation, ty::Binder::dummy(predicate), false)
1950 fn confirm_pointee_candidate<'cx, 'tcx>(
1951 selcx: &mut SelectionContext<'cx, 'tcx>,
1952 obligation: &ProjectionTyObligation<'tcx>,
1953 _: ImplSourcePointeeData,
1954 ) -> Progress<'tcx> {
1955 let tcx = selcx.tcx();
1956 let self_ty = selcx.infcx().shallow_resolve(obligation.predicate.self_ty());
1958 let mut obligations = vec![];
1959 let (metadata_ty, check_is_sized) = self_ty.ptr_metadata_ty(tcx, |ty| {
1960 normalize_with_depth_to(
1962 obligation.param_env,
1963 obligation.cause.clone(),
1964 obligation.recursion_depth + 1,
1970 let sized_predicate = ty::Binder::dummy(ty::TraitRef::new(
1971 tcx.require_lang_item(LangItem::Sized, None),
1972 tcx.mk_substs_trait(self_ty, &[]),
1976 obligations.push(Obligation::new(
1977 obligation.cause.clone(),
1978 obligation.param_env,
1983 let substs = tcx.mk_substs([self_ty.into()].iter());
1984 let metadata_def_id = tcx.require_lang_item(LangItem::Metadata, None);
1986 let predicate = ty::ProjectionPredicate {
1987 projection_ty: ty::ProjectionTy { substs, item_def_id: metadata_def_id },
1988 term: metadata_ty.into(),
1991 confirm_param_env_candidate(selcx, obligation, ty::Binder::dummy(predicate), false)
1992 .with_addl_obligations(obligations)
1995 fn confirm_fn_pointer_candidate<'cx, 'tcx>(
1996 selcx: &mut SelectionContext<'cx, 'tcx>,
1997 obligation: &ProjectionTyObligation<'tcx>,
1998 fn_pointer_impl_source: ImplSourceFnPointerData<'tcx, PredicateObligation<'tcx>>,
1999 ) -> Progress<'tcx> {
2000 let fn_type = selcx.infcx().shallow_resolve(fn_pointer_impl_source.fn_ty);
2001 let sig = fn_type.fn_sig(selcx.tcx());
2002 let Normalized { value: sig, obligations } = normalize_with_depth(
2004 obligation.param_env,
2005 obligation.cause.clone(),
2006 obligation.recursion_depth + 1,
2010 confirm_callable_candidate(selcx, obligation, sig, util::TupleArgumentsFlag::Yes)
2011 .with_addl_obligations(fn_pointer_impl_source.nested)
2012 .with_addl_obligations(obligations)
2015 fn confirm_closure_candidate<'cx, 'tcx>(
2016 selcx: &mut SelectionContext<'cx, 'tcx>,
2017 obligation: &ProjectionTyObligation<'tcx>,
2018 impl_source: ImplSourceClosureData<'tcx, PredicateObligation<'tcx>>,
2019 ) -> Progress<'tcx> {
2020 let closure_sig = impl_source.substs.as_closure().sig();
2021 let Normalized { value: closure_sig, obligations } = normalize_with_depth(
2023 obligation.param_env,
2024 obligation.cause.clone(),
2025 obligation.recursion_depth + 1,
2029 debug!(?obligation, ?closure_sig, ?obligations, "confirm_closure_candidate");
2031 confirm_callable_candidate(selcx, obligation, closure_sig, util::TupleArgumentsFlag::No)
2032 .with_addl_obligations(impl_source.nested)
2033 .with_addl_obligations(obligations)
2036 fn confirm_callable_candidate<'cx, 'tcx>(
2037 selcx: &mut SelectionContext<'cx, 'tcx>,
2038 obligation: &ProjectionTyObligation<'tcx>,
2039 fn_sig: ty::PolyFnSig<'tcx>,
2040 flag: util::TupleArgumentsFlag,
2041 ) -> Progress<'tcx> {
2042 let tcx = selcx.tcx();
2044 debug!(?obligation, ?fn_sig, "confirm_callable_candidate");
2046 let fn_once_def_id = tcx.require_lang_item(LangItem::FnOnce, None);
2047 let fn_once_output_def_id = tcx.require_lang_item(LangItem::FnOnceOutput, None);
2049 let predicate = super::util::closure_trait_ref_and_return_type(
2052 obligation.predicate.self_ty(),
2056 .map_bound(|(trait_ref, ret_type)| ty::ProjectionPredicate {
2057 projection_ty: ty::ProjectionTy {
2058 substs: trait_ref.substs,
2059 item_def_id: fn_once_output_def_id,
2061 term: ret_type.into(),
2064 confirm_param_env_candidate(selcx, obligation, predicate, true)
2067 fn confirm_param_env_candidate<'cx, 'tcx>(
2068 selcx: &mut SelectionContext<'cx, 'tcx>,
2069 obligation: &ProjectionTyObligation<'tcx>,
2070 poly_cache_entry: ty::PolyProjectionPredicate<'tcx>,
2071 potentially_unnormalized_candidate: bool,
2072 ) -> Progress<'tcx> {
2073 let infcx = selcx.infcx();
2074 let cause = &obligation.cause;
2075 let param_env = obligation.param_env;
2077 let cache_entry = infcx.replace_bound_vars_with_fresh_vars(
2079 LateBoundRegionConversionTime::HigherRankedType,
2083 let cache_projection = cache_entry.projection_ty;
2084 let mut nested_obligations = Vec::new();
2085 let obligation_projection = obligation.predicate;
2086 let obligation_projection = ensure_sufficient_stack(|| {
2087 normalize_with_depth_to(
2089 obligation.param_env,
2090 obligation.cause.clone(),
2091 obligation.recursion_depth + 1,
2092 obligation_projection,
2093 &mut nested_obligations,
2096 let cache_projection = if potentially_unnormalized_candidate {
2097 ensure_sufficient_stack(|| {
2098 normalize_with_depth_to(
2100 obligation.param_env,
2101 obligation.cause.clone(),
2102 obligation.recursion_depth + 1,
2104 &mut nested_obligations,
2111 debug!(?cache_projection, ?obligation_projection);
2113 match infcx.at(cause, param_env).eq(cache_projection, obligation_projection) {
2114 Ok(InferOk { value: _, obligations }) => {
2115 nested_obligations.extend(obligations);
2116 assoc_ty_own_obligations(selcx, obligation, &mut nested_obligations);
2117 // FIXME(associated_const_equality): Handle consts here as well? Maybe this progress type should just take
2119 Progress { term: cache_entry.term, obligations: nested_obligations }
2123 "Failed to unify obligation `{:?}` with poly_projection `{:?}`: {:?}",
2124 obligation, poly_cache_entry, e,
2126 debug!("confirm_param_env_candidate: {}", msg);
2127 let err = infcx.tcx.ty_error_with_message(obligation.cause.span, &msg);
2128 Progress { term: err.into(), obligations: vec![] }
2133 fn confirm_impl_candidate<'cx, 'tcx>(
2134 selcx: &mut SelectionContext<'cx, 'tcx>,
2135 obligation: &ProjectionTyObligation<'tcx>,
2136 impl_impl_source: ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>>,
2137 ) -> Progress<'tcx> {
2138 let tcx = selcx.tcx();
2140 let ImplSourceUserDefinedData { impl_def_id, substs, mut nested } = impl_impl_source;
2141 let assoc_item_id = obligation.predicate.item_def_id;
2142 let trait_def_id = tcx.trait_id_of_impl(impl_def_id).unwrap();
2144 let param_env = obligation.param_env;
2145 let Ok(assoc_ty) = assoc_def(selcx, impl_def_id, assoc_item_id) else {
2146 return Progress { term: tcx.ty_error().into(), obligations: nested };
2149 if !assoc_ty.item.defaultness(tcx).has_value() {
2150 // This means that the impl is missing a definition for the
2151 // associated type. This error will be reported by the type
2152 // checker method `check_impl_items_against_trait`, so here we
2153 // just return Error.
2155 "confirm_impl_candidate: no associated type {:?} for {:?}",
2156 assoc_ty.item.name, obligation.predicate
2158 return Progress { term: tcx.ty_error().into(), obligations: nested };
2160 // If we're trying to normalize `<Vec<u32> as X>::A<S>` using
2161 //`impl<T> X for Vec<T> { type A<Y> = Box<Y>; }`, then:
2163 // * `obligation.predicate.substs` is `[Vec<u32>, S]`
2164 // * `substs` is `[u32]`
2165 // * `substs` ends up as `[u32, S]`
2166 let substs = obligation.predicate.substs.rebase_onto(tcx, trait_def_id, substs);
2168 translate_substs(selcx.infcx(), param_env, impl_def_id, substs, assoc_ty.defining_node);
2169 let ty = tcx.bound_type_of(assoc_ty.item.def_id);
2170 let is_const = matches!(tcx.def_kind(assoc_ty.item.def_id), DefKind::AssocConst);
2171 let term: ty::EarlyBinder<ty::Term<'tcx>> = if is_const {
2172 let identity_substs =
2173 crate::traits::InternalSubsts::identity_for_item(tcx, assoc_ty.item.def_id);
2174 let did = ty::WithOptConstParam::unknown(assoc_ty.item.def_id);
2175 let kind = ty::ConstKind::Unevaluated(ty::UnevaluatedConst::new(did, identity_substs));
2176 ty.map_bound(|ty| tcx.mk_const(ty::ConstS { ty, kind }).into())
2178 ty.map_bound(|ty| ty.into())
2180 if !check_substs_compatible(tcx, &assoc_ty.item, substs) {
2181 let err = tcx.ty_error_with_message(
2182 obligation.cause.span,
2183 "impl item and trait item have different parameters",
2185 Progress { term: err.into(), obligations: nested }
2187 assoc_ty_own_obligations(selcx, obligation, &mut nested);
2188 Progress { term: term.subst(tcx, substs), obligations: nested }
2192 // Verify that the trait item and its implementation have compatible substs lists
2193 fn check_substs_compatible<'tcx>(
2195 assoc_ty: &ty::AssocItem,
2196 substs: ty::SubstsRef<'tcx>,
2198 fn check_substs_compatible_inner<'tcx>(
2200 generics: &'tcx ty::Generics,
2201 args: &'tcx [ty::GenericArg<'tcx>],
2203 if generics.count() != args.len() {
2207 let (parent_args, own_args) = args.split_at(generics.parent_count);
2209 if let Some(parent) = generics.parent
2210 && let parent_generics = tcx.generics_of(parent)
2211 && !check_substs_compatible_inner(tcx, parent_generics, parent_args) {
2215 for (param, arg) in std::iter::zip(&generics.params, own_args) {
2216 match (¶m.kind, arg.unpack()) {
2217 (ty::GenericParamDefKind::Type { .. }, ty::GenericArgKind::Type(_))
2218 | (ty::GenericParamDefKind::Lifetime, ty::GenericArgKind::Lifetime(_))
2219 | (ty::GenericParamDefKind::Const { .. }, ty::GenericArgKind::Const(_)) => {}
2227 check_substs_compatible_inner(tcx, tcx.generics_of(assoc_ty.def_id), substs.as_slice())
2230 fn confirm_impl_trait_in_trait_candidate<'tcx>(
2231 selcx: &mut SelectionContext<'_, 'tcx>,
2232 obligation: &ProjectionTyObligation<'tcx>,
2233 data: ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>>,
2234 ) -> Progress<'tcx> {
2235 let tcx = selcx.tcx();
2236 let mut obligations = data.nested;
2238 let trait_fn_def_id = tcx.impl_trait_in_trait_parent(obligation.predicate.item_def_id);
2239 let Ok(leaf_def) = assoc_def(selcx, data.impl_def_id, trait_fn_def_id) else {
2240 return Progress { term: tcx.ty_error().into(), obligations };
2242 if !leaf_def.item.defaultness(tcx).has_value() {
2243 return Progress { term: tcx.ty_error().into(), obligations };
2246 // Use the default `impl Trait` for the trait, e.g., for a default trait body
2247 if leaf_def.item.container == ty::AssocItemContainer::TraitContainer {
2250 .mk_opaque(obligation.predicate.item_def_id, obligation.predicate.substs)
2256 let impl_fn_def_id = leaf_def.item.def_id;
2257 // Rebase from {trait}::{fn}::{opaque} to {impl}::{fn}::{opaque},
2258 // since `data.substs` are the impl substs.
2259 let impl_fn_substs =
2260 obligation.predicate.substs.rebase_onto(tcx, tcx.parent(trait_fn_def_id), data.substs);
2262 let cause = ObligationCause::new(
2263 obligation.cause.span,
2264 obligation.cause.body_id,
2265 super::ItemObligation(impl_fn_def_id),
2267 let predicates = normalize_with_depth_to(
2269 obligation.param_env,
2271 obligation.recursion_depth + 1,
2272 tcx.predicates_of(impl_fn_def_id).instantiate(tcx, impl_fn_substs),
2275 obligations.extend(std::iter::zip(predicates.predicates, predicates.spans).map(
2277 Obligation::with_depth(
2278 ObligationCause::new(
2279 obligation.cause.span,
2280 obligation.cause.body_id,
2281 if span.is_dummy() {
2282 super::ItemObligation(impl_fn_def_id)
2284 super::BindingObligation(impl_fn_def_id, span)
2287 obligation.recursion_depth + 1,
2288 obligation.param_env,
2294 let ty = super::normalize_to(
2296 obligation.param_env,
2298 tcx.bound_trait_impl_trait_tys(impl_fn_def_id)
2300 tys.map_or_else(|_| tcx.ty_error(), |tys| tys[&obligation.predicate.item_def_id])
2302 .subst(tcx, impl_fn_substs),
2306 Progress { term: ty.into(), obligations }
2309 // Get obligations corresponding to the predicates from the where-clause of the
2310 // associated type itself.
2311 fn assoc_ty_own_obligations<'cx, 'tcx>(
2312 selcx: &mut SelectionContext<'cx, 'tcx>,
2313 obligation: &ProjectionTyObligation<'tcx>,
2314 nested: &mut Vec<PredicateObligation<'tcx>>,
2316 let tcx = selcx.tcx();
2317 for predicate in tcx
2318 .predicates_of(obligation.predicate.item_def_id)
2319 .instantiate_own(tcx, obligation.predicate.substs)
2322 let normalized = normalize_with_depth_to(
2324 obligation.param_env,
2325 obligation.cause.clone(),
2326 obligation.recursion_depth + 1,
2330 nested.push(Obligation::with_depth(
2331 obligation.cause.clone(),
2332 obligation.recursion_depth + 1,
2333 obligation.param_env,
2339 /// Locate the definition of an associated type in the specialization hierarchy,
2340 /// starting from the given impl.
2342 /// Based on the "projection mode", this lookup may in fact only examine the
2343 /// topmost impl. See the comments for `Reveal` for more details.
2345 selcx: &SelectionContext<'_, '_>,
2347 assoc_def_id: DefId,
2348 ) -> Result<specialization_graph::LeafDef, ErrorGuaranteed> {
2349 let tcx = selcx.tcx();
2350 let trait_def_id = tcx.impl_trait_ref(impl_def_id).unwrap().def_id;
2351 let trait_def = tcx.trait_def(trait_def_id);
2353 // This function may be called while we are still building the
2354 // specialization graph that is queried below (via TraitDef::ancestors()),
2355 // so, in order to avoid unnecessary infinite recursion, we manually look
2356 // for the associated item at the given impl.
2357 // If there is no such item in that impl, this function will fail with a
2358 // cycle error if the specialization graph is currently being built.
2359 if let Some(&impl_item_id) = tcx.impl_item_implementor_ids(impl_def_id).get(&assoc_def_id) {
2360 let item = tcx.associated_item(impl_item_id);
2361 let impl_node = specialization_graph::Node::Impl(impl_def_id);
2362 return Ok(specialization_graph::LeafDef {
2364 defining_node: impl_node,
2365 finalizing_node: if item.defaultness(tcx).is_default() {
2373 let ancestors = trait_def.ancestors(tcx, impl_def_id)?;
2374 if let Some(assoc_item) = ancestors.leaf_def(tcx, assoc_def_id) {
2377 // This is saying that neither the trait nor
2378 // the impl contain a definition for this
2379 // associated type. Normally this situation
2380 // could only arise through a compiler bug --
2381 // if the user wrote a bad item name, it
2382 // should have failed in astconv.
2384 "No associated type `{}` for {}",
2385 tcx.item_name(assoc_def_id),
2386 tcx.def_path_str(impl_def_id)
2391 pub(crate) trait ProjectionCacheKeyExt<'cx, 'tcx>: Sized {
2392 fn from_poly_projection_predicate(
2393 selcx: &mut SelectionContext<'cx, 'tcx>,
2394 predicate: ty::PolyProjectionPredicate<'tcx>,
2398 impl<'cx, 'tcx> ProjectionCacheKeyExt<'cx, 'tcx> for ProjectionCacheKey<'tcx> {
2399 fn from_poly_projection_predicate(
2400 selcx: &mut SelectionContext<'cx, 'tcx>,
2401 predicate: ty::PolyProjectionPredicate<'tcx>,
2403 let infcx = selcx.infcx();
2404 // We don't do cross-snapshot caching of obligations with escaping regions,
2405 // so there's no cache key to use
2406 predicate.no_bound_vars().map(|predicate| {
2407 ProjectionCacheKey::new(
2408 // We don't attempt to match up with a specific type-variable state
2409 // from a specific call to `opt_normalize_projection_type` - if
2410 // there's no precise match, the original cache entry is "stranded"
2412 infcx.resolve_vars_if_possible(predicate.projection_ty),