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::InferCtxtExt as _;
22 use rustc_data_structures::sso::SsoHashSet;
23 use rustc_data_structures::stack::ensure_sufficient_stack;
24 use rustc_errors::ErrorReported;
25 use rustc_hir::def_id::DefId;
26 use rustc_hir::lang_items::LangItem;
27 use rustc_infer::infer::resolve::OpportunisticRegionResolver;
28 use rustc_middle::ty::fold::{TypeFoldable, TypeFolder};
29 use rustc_middle::ty::subst::Subst;
30 use rustc_middle::ty::{self, ToPredicate, Ty, TyCtxt};
31 use rustc_span::symbol::sym;
33 use std::collections::BTreeMap;
35 pub use rustc_middle::traits::Reveal;
37 pub type PolyProjectionObligation<'tcx> = Obligation<'tcx, ty::PolyProjectionPredicate<'tcx>>;
39 pub type ProjectionObligation<'tcx> = Obligation<'tcx, ty::ProjectionPredicate<'tcx>>;
41 pub type ProjectionTyObligation<'tcx> = Obligation<'tcx, ty::ProjectionTy<'tcx>>;
43 pub(super) struct InProgress;
45 /// When attempting to resolve `<T as TraitRef>::Name` ...
47 pub enum ProjectionTyError<'tcx> {
48 /// ...we found multiple sources of information and couldn't resolve the ambiguity.
51 /// ...an error occurred matching `T : TraitRef`
52 TraitSelectionError(SelectionError<'tcx>),
55 #[derive(PartialEq, Eq, Debug)]
56 enum ProjectionTyCandidate<'tcx> {
57 /// From a where-clause in the env or object type
58 ParamEnv(ty::PolyProjectionPredicate<'tcx>),
60 /// From the definition of `Trait` when you have something like <<A as Trait>::B as Trait2>::C
61 TraitDef(ty::PolyProjectionPredicate<'tcx>),
63 /// Bounds specified on an object type
64 Object(ty::PolyProjectionPredicate<'tcx>),
66 /// From an "impl" (or a "pseudo-impl" returned by select)
67 Select(Selection<'tcx>),
70 enum ProjectionTyCandidateSet<'tcx> {
72 Single(ProjectionTyCandidate<'tcx>),
74 Error(SelectionError<'tcx>),
77 impl<'tcx> ProjectionTyCandidateSet<'tcx> {
78 fn mark_ambiguous(&mut self) {
79 *self = ProjectionTyCandidateSet::Ambiguous;
82 fn mark_error(&mut self, err: SelectionError<'tcx>) {
83 *self = ProjectionTyCandidateSet::Error(err);
86 // Returns true if the push was successful, or false if the candidate
87 // was discarded -- this could be because of ambiguity, or because
88 // a higher-priority candidate is already there.
89 fn push_candidate(&mut self, candidate: ProjectionTyCandidate<'tcx>) -> bool {
90 use self::ProjectionTyCandidate::*;
91 use self::ProjectionTyCandidateSet::*;
93 // This wacky variable is just used to try and
94 // make code readable and avoid confusing paths.
95 // It is assigned a "value" of `()` only on those
96 // paths in which we wish to convert `*self` to
97 // ambiguous (and return false, because the candidate
98 // was not used). On other paths, it is not assigned,
99 // and hence if those paths *could* reach the code that
100 // comes after the match, this fn would not compile.
101 let convert_to_ambiguous;
105 *self = Single(candidate);
110 // Duplicates can happen inside ParamEnv. In the case, we
111 // perform a lazy deduplication.
112 if current == &candidate {
116 // Prefer where-clauses. As in select, if there are multiple
117 // candidates, we prefer where-clause candidates over impls. This
118 // may seem a bit surprising, since impls are the source of
119 // "truth" in some sense, but in fact some of the impls that SEEM
120 // applicable are not, because of nested obligations. Where
121 // clauses are the safer choice. See the comment on
122 // `select::SelectionCandidate` and #21974 for more details.
123 match (current, candidate) {
124 (ParamEnv(..), ParamEnv(..)) => convert_to_ambiguous = (),
125 (ParamEnv(..), _) => return false,
126 (_, ParamEnv(..)) => unreachable!(),
127 (_, _) => convert_to_ambiguous = (),
131 Ambiguous | Error(..) => {
136 // We only ever get here when we moved from a single candidate
138 let () = convert_to_ambiguous;
144 /// Evaluates constraints of the form:
146 /// for<...> <T as Trait>::U == V
148 /// If successful, this may result in additional obligations. Also returns
149 /// the projection cache key used to track these additional obligations.
153 /// - `Err(_)`: the projection can be normalized, but is not equal to the
155 /// - `Ok(Err(InProgress))`: this is called recursively while normalizing
156 /// the same projection.
157 /// - `Ok(Ok(None))`: The projection cannot be normalized due to ambiguity
158 /// (resolving some inference variables in the projection may fix this).
159 /// - `Ok(Ok(Some(obligations)))`: The projection bound holds subject to
160 /// the given obligations. If the projection cannot be normalized because
161 /// the required trait bound doesn't hold this returned with `obligations`
162 /// being a predicate that cannot be proven.
163 #[instrument(level = "debug", skip(selcx))]
164 pub(super) fn poly_project_and_unify_type<'cx, 'tcx>(
165 selcx: &mut SelectionContext<'cx, 'tcx>,
166 obligation: &PolyProjectionObligation<'tcx>,
168 Result<Option<Vec<PredicateObligation<'tcx>>>, InProgress>,
169 MismatchedProjectionTypes<'tcx>,
171 let infcx = selcx.infcx();
172 infcx.commit_if_ok(|_snapshot| {
173 let placeholder_predicate =
174 infcx.replace_bound_vars_with_placeholders(obligation.predicate);
176 let placeholder_obligation = obligation.with(placeholder_predicate);
177 let result = project_and_unify_type(selcx, &placeholder_obligation)?;
182 /// Evaluates constraints of the form:
184 /// <T as Trait>::U == V
186 /// If successful, this may result in additional obligations.
188 /// See [poly_project_and_unify_type] for an explanation of the return value.
189 fn project_and_unify_type<'cx, 'tcx>(
190 selcx: &mut SelectionContext<'cx, 'tcx>,
191 obligation: &ProjectionObligation<'tcx>,
193 Result<Option<Vec<PredicateObligation<'tcx>>>, InProgress>,
194 MismatchedProjectionTypes<'tcx>,
196 debug!(?obligation, "project_and_unify_type");
198 let mut obligations = vec![];
199 let normalized_ty = match opt_normalize_projection_type(
201 obligation.param_env,
202 obligation.predicate.projection_ty,
203 obligation.cause.clone(),
204 obligation.recursion_depth,
208 Ok(None) => return Ok(Ok(None)),
209 Err(InProgress) => return Ok(Err(InProgress)),
212 debug!(?normalized_ty, ?obligations, "project_and_unify_type result");
214 let infcx = selcx.infcx();
216 .at(&obligation.cause, obligation.param_env)
217 .eq(normalized_ty, obligation.predicate.term.ty())
219 Ok(InferOk { obligations: inferred_obligations, value: () }) => {
220 obligations.extend(inferred_obligations);
221 Ok(Ok(Some(obligations)))
224 debug!("project_and_unify_type: equating types encountered error {:?}", err);
225 Err(MismatchedProjectionTypes { err })
230 /// Normalizes any associated type projections in `value`, replacing
231 /// them with a fully resolved type where possible. The return value
232 /// combines the normalized result and any additional obligations that
233 /// were incurred as result.
234 pub fn normalize<'a, 'b, 'tcx, T>(
235 selcx: &'a mut SelectionContext<'b, 'tcx>,
236 param_env: ty::ParamEnv<'tcx>,
237 cause: ObligationCause<'tcx>,
239 ) -> Normalized<'tcx, T>
241 T: TypeFoldable<'tcx>,
243 let mut obligations = Vec::new();
244 let value = normalize_to(selcx, param_env, cause, value, &mut obligations);
245 Normalized { value, obligations }
248 pub fn normalize_to<'a, 'b, 'tcx, T>(
249 selcx: &'a mut SelectionContext<'b, 'tcx>,
250 param_env: ty::ParamEnv<'tcx>,
251 cause: ObligationCause<'tcx>,
253 obligations: &mut Vec<PredicateObligation<'tcx>>,
256 T: TypeFoldable<'tcx>,
258 normalize_with_depth_to(selcx, param_env, cause, 0, value, obligations)
261 /// As `normalize`, but with a custom depth.
262 pub fn normalize_with_depth<'a, 'b, 'tcx, T>(
263 selcx: &'a mut SelectionContext<'b, 'tcx>,
264 param_env: ty::ParamEnv<'tcx>,
265 cause: ObligationCause<'tcx>,
268 ) -> Normalized<'tcx, T>
270 T: TypeFoldable<'tcx>,
272 let mut obligations = Vec::new();
273 let value = normalize_with_depth_to(selcx, param_env, cause, depth, value, &mut obligations);
274 Normalized { value, obligations }
277 #[instrument(level = "info", skip(selcx, param_env, cause, obligations))]
278 pub fn normalize_with_depth_to<'a, 'b, 'tcx, T>(
279 selcx: &'a mut SelectionContext<'b, 'tcx>,
280 param_env: ty::ParamEnv<'tcx>,
281 cause: ObligationCause<'tcx>,
284 obligations: &mut Vec<PredicateObligation<'tcx>>,
287 T: TypeFoldable<'tcx>,
289 debug!(obligations.len = obligations.len());
290 let mut normalizer = AssocTypeNormalizer::new(selcx, param_env, cause, depth, obligations);
291 let result = ensure_sufficient_stack(|| normalizer.fold(value));
292 debug!(?result, obligations.len = normalizer.obligations.len());
293 debug!(?normalizer.obligations,);
297 pub(crate) fn needs_normalization<'tcx, T: TypeFoldable<'tcx>>(value: &T, reveal: Reveal) -> bool {
299 Reveal::UserFacing => value
300 .has_type_flags(ty::TypeFlags::HAS_TY_PROJECTION | ty::TypeFlags::HAS_CT_PROJECTION),
301 Reveal::All => value.has_type_flags(
302 ty::TypeFlags::HAS_TY_PROJECTION
303 | ty::TypeFlags::HAS_TY_OPAQUE
304 | ty::TypeFlags::HAS_CT_PROJECTION,
309 struct AssocTypeNormalizer<'a, 'b, 'tcx> {
310 selcx: &'a mut SelectionContext<'b, 'tcx>,
311 param_env: ty::ParamEnv<'tcx>,
312 cause: ObligationCause<'tcx>,
313 obligations: &'a mut Vec<PredicateObligation<'tcx>>,
315 universes: Vec<Option<ty::UniverseIndex>>,
318 impl<'a, 'b, 'tcx> AssocTypeNormalizer<'a, 'b, 'tcx> {
320 selcx: &'a mut SelectionContext<'b, 'tcx>,
321 param_env: ty::ParamEnv<'tcx>,
322 cause: ObligationCause<'tcx>,
324 obligations: &'a mut Vec<PredicateObligation<'tcx>>,
325 ) -> AssocTypeNormalizer<'a, 'b, 'tcx> {
326 AssocTypeNormalizer { selcx, param_env, cause, obligations, depth, universes: vec![] }
329 fn fold<T: TypeFoldable<'tcx>>(&mut self, value: T) -> T {
330 let value = self.selcx.infcx().resolve_vars_if_possible(value);
334 !value.has_escaping_bound_vars(),
335 "Normalizing {:?} without wrapping in a `Binder`",
339 if !needs_normalization(&value, self.param_env.reveal()) {
342 value.fold_with(self)
347 impl<'a, 'b, 'tcx> TypeFolder<'tcx> for AssocTypeNormalizer<'a, 'b, 'tcx> {
348 fn tcx<'c>(&'c self) -> TyCtxt<'tcx> {
352 fn fold_binder<T: TypeFoldable<'tcx>>(
354 t: ty::Binder<'tcx, T>,
355 ) -> ty::Binder<'tcx, T> {
356 self.universes.push(None);
357 let t = t.super_fold_with(self);
358 self.universes.pop();
362 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
363 if !needs_normalization(&ty, self.param_env.reveal()) {
367 // We try to be a little clever here as a performance optimization in
368 // cases where there are nested projections under binders.
371 // for<'a> fn(<T as Foo>::One<'a, Box<dyn Bar<'a, Item=<T as Foo>::Two<'a>>>>)
373 // We normalize the substs on the projection before the projecting, but
374 // if we're naive, we'll
375 // replace bound vars on inner, project inner, replace placeholders on inner,
376 // replace bound vars on outer, project outer, replace placeholders on outer
378 // However, if we're a bit more clever, we can replace the bound vars
379 // on the entire type before normalizing nested projections, meaning we
380 // replace bound vars on outer, project inner,
381 // project outer, replace placeholders on outer
383 // This is possible because the inner `'a` will already be a placeholder
384 // when we need to normalize the inner projection
386 // On the other hand, this does add a bit of complexity, since we only
387 // replace bound vars if the current type is a `Projection` and we need
388 // to make sure we don't forget to fold the substs regardless.
391 // This is really important. While we *can* handle this, this has
392 // severe performance implications for large opaque types with
393 // late-bound regions. See `issue-88862` benchmark.
394 ty::Opaque(def_id, substs) if !substs.has_escaping_bound_vars() => {
395 // Only normalize `impl Trait` after type-checking, usually in codegen.
396 match self.param_env.reveal() {
397 Reveal::UserFacing => ty.super_fold_with(self),
400 let recursion_limit = self.tcx().recursion_limit();
401 if !recursion_limit.value_within_limit(self.depth) {
402 let obligation = Obligation::with_depth(
408 self.selcx.infcx().report_overflow_error(&obligation, true);
411 let substs = substs.super_fold_with(self);
412 let generic_ty = self.tcx().type_of(def_id);
413 let concrete_ty = generic_ty.subst(self.tcx(), substs);
415 let folded_ty = self.fold_ty(concrete_ty);
422 ty::Projection(data) if !data.has_escaping_bound_vars() => {
423 // This branch is *mostly* just an optimization: when we don't
424 // have escaping bound vars, we don't need to replace them with
425 // placeholders (see branch below). *Also*, we know that we can
426 // register an obligation to *later* project, since we know
427 // there won't be bound vars there.
429 let data = data.super_fold_with(self);
430 let normalized_ty = normalize_projection_type(
436 &mut self.obligations,
442 obligations.len = ?self.obligations.len(),
443 "AssocTypeNormalizer: normalized type"
448 ty::Projection(data) => {
449 // If there are escaping bound vars, we temporarily replace the
450 // bound vars with placeholders. Note though, that in the case
451 // that we still can't project for whatever reason (e.g. self
452 // type isn't known enough), we *can't* register an obligation
453 // and return an inference variable (since then that obligation
454 // would have bound vars and that's a can of worms). Instead,
455 // we just give up and fall back to pretending like we never tried!
457 // Note: this isn't necessarily the final approach here; we may
458 // want to figure out how to register obligations with escaping vars
459 // or handle this some other way.
461 let infcx = self.selcx.infcx();
462 let (data, mapped_regions, mapped_types, mapped_consts) =
463 BoundVarReplacer::replace_bound_vars(infcx, &mut self.universes, data);
464 let data = data.super_fold_with(self);
465 let normalized_ty = opt_normalize_projection_type(
471 &mut self.obligations,
475 .map(|normalized_ty| {
476 PlaceholderReplacer::replace_placeholders(
485 .unwrap_or_else(|| ty.super_fold_with(self));
491 obligations.len = ?self.obligations.len(),
492 "AssocTypeNormalizer: normalized type"
497 _ => ty.super_fold_with(self),
501 fn fold_const(&mut self, constant: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
502 if self.selcx.tcx().lazy_normalization() {
505 let constant = constant.super_fold_with(self);
506 constant.eval(self.selcx.tcx(), self.param_env)
511 pub struct BoundVarReplacer<'me, 'tcx> {
512 infcx: &'me InferCtxt<'me, 'tcx>,
513 // These three maps track the bound variable that were replaced by placeholders. It might be
514 // nice to remove these since we already have the `kind` in the placeholder; we really just need
515 // the `var` (but we *could* bring that into scope if we were to track them as we pass them).
516 mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
517 mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy>,
518 mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
519 // The current depth relative to *this* folding, *not* the entire normalization. In other words,
520 // the depth of binders we've passed here.
521 current_index: ty::DebruijnIndex,
522 // The `UniverseIndex` of the binding levels above us. These are optional, since we are lazy:
523 // we don't actually create a universe until we see a bound var we have to replace.
524 universe_indices: &'me mut Vec<Option<ty::UniverseIndex>>,
527 impl<'me, 'tcx> BoundVarReplacer<'me, 'tcx> {
528 /// Returns `Some` if we *were* able to replace bound vars. If there are any bound vars that
529 /// use a binding level above `universe_indices.len()`, we fail.
530 pub fn replace_bound_vars<T: TypeFoldable<'tcx>>(
531 infcx: &'me InferCtxt<'me, 'tcx>,
532 universe_indices: &'me mut Vec<Option<ty::UniverseIndex>>,
536 BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
537 BTreeMap<ty::PlaceholderType, ty::BoundTy>,
538 BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
540 let mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion> = BTreeMap::new();
541 let mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy> = BTreeMap::new();
542 let mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar> = BTreeMap::new();
544 let mut replacer = BoundVarReplacer {
549 current_index: ty::INNERMOST,
553 let value = value.super_fold_with(&mut replacer);
555 (value, replacer.mapped_regions, replacer.mapped_types, replacer.mapped_consts)
558 fn universe_for(&mut self, debruijn: ty::DebruijnIndex) -> ty::UniverseIndex {
559 let infcx = self.infcx;
561 self.universe_indices.len() + self.current_index.as_usize() - debruijn.as_usize() - 1;
562 let universe = self.universe_indices[index].unwrap_or_else(|| {
563 for i in self.universe_indices.iter_mut().take(index + 1) {
564 *i = i.or_else(|| Some(infcx.create_next_universe()))
566 self.universe_indices[index].unwrap()
572 impl<'tcx> TypeFolder<'tcx> for BoundVarReplacer<'_, 'tcx> {
573 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
577 fn fold_binder<T: TypeFoldable<'tcx>>(
579 t: ty::Binder<'tcx, T>,
580 ) -> ty::Binder<'tcx, T> {
581 self.current_index.shift_in(1);
582 let t = t.super_fold_with(self);
583 self.current_index.shift_out(1);
587 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
589 ty::ReLateBound(debruijn, _)
590 if debruijn.as_usize() + 1
591 > self.current_index.as_usize() + self.universe_indices.len() =>
593 bug!("Bound vars outside of `self.universe_indices`");
595 ty::ReLateBound(debruijn, br) if debruijn >= self.current_index => {
596 let universe = self.universe_for(debruijn);
597 let p = ty::PlaceholderRegion { universe, name: br.kind };
598 self.mapped_regions.insert(p, br);
599 self.infcx.tcx.mk_region(ty::RePlaceholder(p))
605 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
607 ty::Bound(debruijn, _)
608 if debruijn.as_usize() + 1
609 > self.current_index.as_usize() + self.universe_indices.len() =>
611 bug!("Bound vars outside of `self.universe_indices`");
613 ty::Bound(debruijn, bound_ty) if debruijn >= self.current_index => {
614 let universe = self.universe_for(debruijn);
615 let p = ty::PlaceholderType { universe, name: bound_ty.var };
616 self.mapped_types.insert(p, bound_ty);
617 self.infcx.tcx.mk_ty(ty::Placeholder(p))
619 _ if t.has_vars_bound_at_or_above(self.current_index) => t.super_fold_with(self),
624 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
626 ty::Const { val: ty::ConstKind::Bound(debruijn, _), ty: _ }
627 if debruijn.as_usize() + 1
628 > self.current_index.as_usize() + self.universe_indices.len() =>
630 bug!("Bound vars outside of `self.universe_indices`");
632 ty::Const { val: ty::ConstKind::Bound(debruijn, bound_const), ty }
633 if debruijn >= self.current_index =>
635 let universe = self.universe_for(debruijn);
636 let p = ty::PlaceholderConst {
638 name: ty::BoundConst { var: bound_const, ty },
640 self.mapped_consts.insert(p, bound_const);
641 self.infcx.tcx.mk_const(ty::Const { val: ty::ConstKind::Placeholder(p), ty })
643 _ if ct.has_vars_bound_at_or_above(self.current_index) => ct.super_fold_with(self),
649 // The inverse of `BoundVarReplacer`: replaces placeholders with the bound vars from which they came.
650 pub struct PlaceholderReplacer<'me, 'tcx> {
651 infcx: &'me InferCtxt<'me, 'tcx>,
652 mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
653 mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy>,
654 mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
655 universe_indices: &'me Vec<Option<ty::UniverseIndex>>,
656 current_index: ty::DebruijnIndex,
659 impl<'me, 'tcx> PlaceholderReplacer<'me, 'tcx> {
660 pub fn replace_placeholders<T: TypeFoldable<'tcx>>(
661 infcx: &'me InferCtxt<'me, 'tcx>,
662 mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
663 mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy>,
664 mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
665 universe_indices: &'me Vec<Option<ty::UniverseIndex>>,
668 let mut replacer = PlaceholderReplacer {
674 current_index: ty::INNERMOST,
676 value.super_fold_with(&mut replacer)
680 impl<'tcx> TypeFolder<'tcx> for PlaceholderReplacer<'_, 'tcx> {
681 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
685 fn fold_binder<T: TypeFoldable<'tcx>>(
687 t: ty::Binder<'tcx, T>,
688 ) -> ty::Binder<'tcx, T> {
689 if !t.has_placeholders() && !t.has_infer_regions() {
692 self.current_index.shift_in(1);
693 let t = t.super_fold_with(self);
694 self.current_index.shift_out(1);
698 fn fold_region(&mut self, r0: ty::Region<'tcx>) -> ty::Region<'tcx> {
704 .unwrap_region_constraints()
705 .opportunistic_resolve_region(self.infcx.tcx, r0),
710 ty::RePlaceholder(p) => {
711 let replace_var = self.mapped_regions.get(&p);
713 Some(replace_var) => {
717 .position(|u| matches!(u, Some(pu) if *pu == p.universe))
718 .unwrap_or_else(|| bug!("Unexpected placeholder universe."));
719 let db = ty::DebruijnIndex::from_usize(
720 self.universe_indices.len() - index + self.current_index.as_usize() - 1,
722 self.tcx().mk_region(ty::ReLateBound(db, *replace_var))
730 debug!(?r0, ?r1, ?r2, "fold_region");
735 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
737 ty::Placeholder(p) => {
738 let replace_var = self.mapped_types.get(&p);
740 Some(replace_var) => {
744 .position(|u| matches!(u, Some(pu) if *pu == p.universe))
745 .unwrap_or_else(|| bug!("Unexpected placeholder universe."));
746 let db = ty::DebruijnIndex::from_usize(
747 self.universe_indices.len() - index + self.current_index.as_usize() - 1,
749 self.tcx().mk_ty(ty::Bound(db, *replace_var))
755 _ if ty.has_placeholders() || ty.has_infer_regions() => ty.super_fold_with(self),
760 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
761 if let ty::Const { val: ty::ConstKind::Placeholder(p), ty } = *ct {
762 let replace_var = self.mapped_consts.get(&p);
764 Some(replace_var) => {
768 .position(|u| matches!(u, Some(pu) if *pu == p.universe))
769 .unwrap_or_else(|| bug!("Unexpected placeholder universe."));
770 let db = ty::DebruijnIndex::from_usize(
771 self.universe_indices.len() - index + self.current_index.as_usize() - 1,
774 .mk_const(ty::Const { val: ty::ConstKind::Bound(db, *replace_var), ty })
779 ct.super_fold_with(self)
784 /// The guts of `normalize`: normalize a specific projection like `<T
785 /// as Trait>::Item`. The result is always a type (and possibly
786 /// additional obligations). If ambiguity arises, which implies that
787 /// there are unresolved type variables in the projection, we will
788 /// substitute a fresh type variable `$X` and generate a new
789 /// obligation `<T as Trait>::Item == $X` for later.
790 pub fn normalize_projection_type<'a, 'b, 'tcx>(
791 selcx: &'a mut SelectionContext<'b, 'tcx>,
792 param_env: ty::ParamEnv<'tcx>,
793 projection_ty: ty::ProjectionTy<'tcx>,
794 cause: ObligationCause<'tcx>,
796 obligations: &mut Vec<PredicateObligation<'tcx>>,
798 opt_normalize_projection_type(
808 .unwrap_or_else(move || {
809 // if we bottom out in ambiguity, create a type variable
810 // and a deferred predicate to resolve this when more type
811 // information is available.
813 selcx.infcx().infer_projection(param_env, projection_ty, cause, depth + 1, obligations)
817 /// The guts of `normalize`: normalize a specific projection like `<T
818 /// as Trait>::Item`. The result is always a type (and possibly
819 /// additional obligations). Returns `None` in the case of ambiguity,
820 /// which indicates that there are unbound type variables.
822 /// This function used to return `Option<NormalizedTy<'tcx>>`, which contains a
823 /// `Ty<'tcx>` and an obligations vector. But that obligation vector was very
824 /// often immediately appended to another obligations vector. So now this
825 /// function takes an obligations vector and appends to it directly, which is
826 /// slightly uglier but avoids the need for an extra short-lived allocation.
827 #[instrument(level = "debug", skip(selcx, param_env, cause, obligations))]
828 fn opt_normalize_projection_type<'a, 'b, 'tcx>(
829 selcx: &'a mut SelectionContext<'b, 'tcx>,
830 param_env: ty::ParamEnv<'tcx>,
831 projection_ty: ty::ProjectionTy<'tcx>,
832 cause: ObligationCause<'tcx>,
834 obligations: &mut Vec<PredicateObligation<'tcx>>,
835 ) -> Result<Option<Ty<'tcx>>, InProgress> {
836 let infcx = selcx.infcx();
837 // Don't use the projection cache in intercrate mode -
838 // the `infcx` may be re-used between intercrate in non-intercrate
839 // mode, which could lead to using incorrect cache results.
840 let use_cache = !selcx.is_intercrate();
842 let projection_ty = infcx.resolve_vars_if_possible(projection_ty);
843 let cache_key = ProjectionCacheKey::new(projection_ty);
845 // FIXME(#20304) For now, I am caching here, which is good, but it
846 // means we don't capture the type variables that are created in
847 // the case of ambiguity. Which means we may create a large stream
848 // of such variables. OTOH, if we move the caching up a level, we
849 // would not benefit from caching when proving `T: Trait<U=Foo>`
850 // bounds. It might be the case that we want two distinct caches,
851 // or else another kind of cache entry.
853 let cache_result = if use_cache {
854 infcx.inner.borrow_mut().projection_cache().try_start(cache_key)
859 Ok(()) => debug!("no cache"),
860 Err(ProjectionCacheEntry::Ambiguous) => {
861 // If we found ambiguity the last time, that means we will continue
862 // to do so until some type in the key changes (and we know it
863 // hasn't, because we just fully resolved it).
864 debug!("found cache entry: ambiguous");
867 Err(ProjectionCacheEntry::InProgress) => {
868 // Under lazy normalization, this can arise when
869 // bootstrapping. That is, imagine an environment with a
870 // where-clause like `A::B == u32`. Now, if we are asked
871 // to normalize `A::B`, we will want to check the
872 // where-clauses in scope. So we will try to unify `A::B`
873 // with `A::B`, which can trigger a recursive
876 debug!("found cache entry: in-progress");
878 // Cache that normalizing this projection resulted in a cycle. This
879 // should ensure that, unless this happens within a snapshot that's
880 // rolled back, fulfillment or evaluation will notice the cycle.
883 infcx.inner.borrow_mut().projection_cache().recur(cache_key);
885 return Err(InProgress);
887 Err(ProjectionCacheEntry::Recur) => {
888 debug!("recur cache");
889 return Err(InProgress);
891 Err(ProjectionCacheEntry::NormalizedTy { ty, complete: _ }) => {
892 // This is the hottest path in this function.
894 // If we find the value in the cache, then return it along
895 // with the obligations that went along with it. Note
896 // that, when using a fulfillment context, these
897 // obligations could in principle be ignored: they have
898 // already been registered when the cache entry was
899 // created (and hence the new ones will quickly be
900 // discarded as duplicated). But when doing trait
901 // evaluation this is not the case, and dropping the trait
902 // evaluations can causes ICEs (e.g., #43132).
903 debug!(?ty, "found normalized ty");
904 obligations.extend(ty.obligations);
905 return Ok(Some(ty.value));
907 Err(ProjectionCacheEntry::Error) => {
908 debug!("opt_normalize_projection_type: found error");
909 let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth);
910 obligations.extend(result.obligations);
911 return Ok(Some(result.value));
915 let obligation = Obligation::with_depth(cause.clone(), depth, param_env, projection_ty);
917 match project_type(selcx, &obligation) {
918 Ok(ProjectedTy::Progress(Progress {
920 obligations: mut projected_obligations,
922 // if projection succeeded, then what we get out of this
923 // is also non-normalized (consider: it was derived from
924 // an impl, where-clause etc) and hence we must
927 let projected_ty = selcx.infcx().resolve_vars_if_possible(projected_ty);
928 debug!(?projected_ty, ?depth, ?projected_obligations);
930 let mut result = if projected_ty.has_projections() {
931 let mut normalizer = AssocTypeNormalizer::new(
936 &mut projected_obligations,
938 let normalized_ty = normalizer.fold(projected_ty);
940 debug!(?normalized_ty, ?depth);
942 Normalized { value: normalized_ty, obligations: projected_obligations }
944 Normalized { value: projected_ty, obligations: projected_obligations }
947 let mut deduped: SsoHashSet<_> = Default::default();
948 result.obligations.drain_filter(|projected_obligation| {
949 if !deduped.insert(projected_obligation.clone()) {
956 infcx.inner.borrow_mut().projection_cache().insert_ty(cache_key, result.clone());
958 obligations.extend(result.obligations);
959 Ok(Some(result.value))
961 Ok(ProjectedTy::NoProgress(projected_ty)) => {
962 debug!(?projected_ty, "opt_normalize_projection_type: no progress");
963 let result = Normalized { value: projected_ty, obligations: vec![] };
965 infcx.inner.borrow_mut().projection_cache().insert_ty(cache_key, result.clone());
967 // No need to extend `obligations`.
968 Ok(Some(result.value))
970 Err(ProjectionTyError::TooManyCandidates) => {
971 debug!("opt_normalize_projection_type: too many candidates");
973 infcx.inner.borrow_mut().projection_cache().ambiguous(cache_key);
977 Err(ProjectionTyError::TraitSelectionError(_)) => {
978 debug!("opt_normalize_projection_type: ERROR");
979 // if we got an error processing the `T as Trait` part,
980 // just return `ty::err` but add the obligation `T :
981 // Trait`, which when processed will cause the error to be
985 infcx.inner.borrow_mut().projection_cache().error(cache_key);
987 let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth);
988 obligations.extend(result.obligations);
989 Ok(Some(result.value))
994 /// If we are projecting `<T as Trait>::Item`, but `T: Trait` does not
995 /// hold. In various error cases, we cannot generate a valid
996 /// normalized projection. Therefore, we create an inference variable
997 /// return an associated obligation that, when fulfilled, will lead to
1000 /// Note that we used to return `Error` here, but that was quite
1001 /// dubious -- the premise was that an error would *eventually* be
1002 /// reported, when the obligation was processed. But in general once
1003 /// you see an `Error` you are supposed to be able to assume that an
1004 /// error *has been* reported, so that you can take whatever heuristic
1005 /// paths you want to take. To make things worse, it was possible for
1006 /// cycles to arise, where you basically had a setup like `<MyType<$0>
1007 /// as Trait>::Foo == $0`. Here, normalizing `<MyType<$0> as
1008 /// Trait>::Foo> to `[type error]` would lead to an obligation of
1009 /// `<MyType<[type error]> as Trait>::Foo`. We are supposed to report
1010 /// an error for this obligation, but we legitimately should not,
1011 /// because it contains `[type error]`. Yuck! (See issue #29857 for
1012 /// one case where this arose.)
1013 fn normalize_to_error<'a, 'tcx>(
1014 selcx: &mut SelectionContext<'a, 'tcx>,
1015 param_env: ty::ParamEnv<'tcx>,
1016 projection_ty: ty::ProjectionTy<'tcx>,
1017 cause: ObligationCause<'tcx>,
1019 ) -> NormalizedTy<'tcx> {
1020 let trait_ref = ty::Binder::dummy(projection_ty.trait_ref(selcx.tcx()));
1021 let trait_obligation = Obligation {
1023 recursion_depth: depth,
1025 predicate: trait_ref.without_const().to_predicate(selcx.tcx()),
1027 let tcx = selcx.infcx().tcx;
1028 let def_id = projection_ty.item_def_id;
1029 let new_value = selcx.infcx().next_ty_var(TypeVariableOrigin {
1030 kind: TypeVariableOriginKind::NormalizeProjectionType,
1031 span: tcx.def_span(def_id),
1033 Normalized { value: new_value, obligations: vec![trait_obligation] }
1036 enum ProjectedTy<'tcx> {
1037 Progress(Progress<'tcx>),
1038 NoProgress(Ty<'tcx>),
1041 struct Progress<'tcx> {
1043 obligations: Vec<PredicateObligation<'tcx>>,
1046 impl<'tcx> Progress<'tcx> {
1047 fn error(tcx: TyCtxt<'tcx>) -> Self {
1048 Progress { ty: tcx.ty_error(), obligations: vec![] }
1051 fn with_addl_obligations(mut self, mut obligations: Vec<PredicateObligation<'tcx>>) -> Self {
1053 self.obligations.len = ?self.obligations.len(),
1054 obligations.len = obligations.len(),
1055 "with_addl_obligations"
1058 debug!(?self.obligations, ?obligations, "with_addl_obligations");
1060 self.obligations.append(&mut obligations);
1065 /// Computes the result of a projection type (if we can).
1068 /// - `obligation` must be fully normalized
1069 #[tracing::instrument(level = "info", skip(selcx))]
1070 fn project_type<'cx, 'tcx>(
1071 selcx: &mut SelectionContext<'cx, 'tcx>,
1072 obligation: &ProjectionTyObligation<'tcx>,
1073 ) -> Result<ProjectedTy<'tcx>, ProjectionTyError<'tcx>> {
1074 if !selcx.tcx().recursion_limit().value_within_limit(obligation.recursion_depth) {
1075 debug!("project: overflow!");
1076 // This should really be an immediate error, but some existing code
1077 // relies on being able to recover from this.
1078 return Err(ProjectionTyError::TraitSelectionError(SelectionError::Overflow));
1081 if obligation.predicate.references_error() {
1082 return Ok(ProjectedTy::Progress(Progress::error(selcx.tcx())));
1085 let mut candidates = ProjectionTyCandidateSet::None;
1087 // Make sure that the following procedures are kept in order. ParamEnv
1088 // needs to be first because it has highest priority, and Select checks
1089 // the return value of push_candidate which assumes it's ran at last.
1090 assemble_candidates_from_param_env(selcx, obligation, &mut candidates);
1092 assemble_candidates_from_trait_def(selcx, obligation, &mut candidates);
1094 assemble_candidates_from_object_ty(selcx, obligation, &mut candidates);
1096 if let ProjectionTyCandidateSet::Single(ProjectionTyCandidate::Object(_)) = candidates {
1097 // Avoid normalization cycle from selection (see
1098 // `assemble_candidates_from_object_ty`).
1099 // FIXME(lazy_normalization): Lazy normalization should save us from
1100 // having to special case this.
1102 assemble_candidates_from_impls(selcx, obligation, &mut candidates);
1106 ProjectionTyCandidateSet::Single(candidate) => {
1107 Ok(ProjectedTy::Progress(confirm_candidate(selcx, obligation, candidate)))
1109 ProjectionTyCandidateSet::None => Ok(ProjectedTy::NoProgress(
1112 .mk_projection(obligation.predicate.item_def_id, obligation.predicate.substs),
1114 // Error occurred while trying to processing impls.
1115 ProjectionTyCandidateSet::Error(e) => Err(ProjectionTyError::TraitSelectionError(e)),
1116 // Inherent ambiguity that prevents us from even enumerating the
1118 ProjectionTyCandidateSet::Ambiguous => Err(ProjectionTyError::TooManyCandidates),
1122 /// The first thing we have to do is scan through the parameter
1123 /// environment to see whether there are any projection predicates
1124 /// there that can answer this question.
1125 fn assemble_candidates_from_param_env<'cx, 'tcx>(
1126 selcx: &mut SelectionContext<'cx, 'tcx>,
1127 obligation: &ProjectionTyObligation<'tcx>,
1128 candidate_set: &mut ProjectionTyCandidateSet<'tcx>,
1130 debug!("assemble_candidates_from_param_env(..)");
1131 assemble_candidates_from_predicates(
1135 ProjectionTyCandidate::ParamEnv,
1136 obligation.param_env.caller_bounds().iter(),
1141 /// In the case of a nested projection like <<A as Foo>::FooT as Bar>::BarT, we may find
1142 /// that the definition of `Foo` has some clues:
1146 /// type FooT : Bar<BarT=i32>
1150 /// Here, for example, we could conclude that the result is `i32`.
1151 fn assemble_candidates_from_trait_def<'cx, 'tcx>(
1152 selcx: &mut SelectionContext<'cx, 'tcx>,
1153 obligation: &ProjectionTyObligation<'tcx>,
1154 candidate_set: &mut ProjectionTyCandidateSet<'tcx>,
1156 debug!("assemble_candidates_from_trait_def(..)");
1158 let tcx = selcx.tcx();
1159 // Check whether the self-type is itself a projection.
1160 // If so, extract what we know from the trait and try to come up with a good answer.
1161 let bounds = match *obligation.predicate.self_ty().kind() {
1162 ty::Projection(ref data) => tcx.item_bounds(data.item_def_id).subst(tcx, data.substs),
1163 ty::Opaque(def_id, substs) => tcx.item_bounds(def_id).subst(tcx, substs),
1164 ty::Infer(ty::TyVar(_)) => {
1165 // If the self-type is an inference variable, then it MAY wind up
1166 // being a projected type, so induce an ambiguity.
1167 candidate_set.mark_ambiguous();
1173 assemble_candidates_from_predicates(
1177 ProjectionTyCandidate::TraitDef,
1183 /// In the case of a trait object like
1184 /// `<dyn Iterator<Item = ()> as Iterator>::Item` we can use the existential
1185 /// predicate in the trait object.
1187 /// We don't go through the select candidate for these bounds to avoid cycles:
1188 /// In the above case, `dyn Iterator<Item = ()>: Iterator` would create a
1189 /// nested obligation of `<dyn Iterator<Item = ()> as Iterator>::Item: Sized`,
1190 /// this then has to be normalized without having to prove
1191 /// `dyn Iterator<Item = ()>: Iterator` again.
1192 fn assemble_candidates_from_object_ty<'cx, 'tcx>(
1193 selcx: &mut SelectionContext<'cx, 'tcx>,
1194 obligation: &ProjectionTyObligation<'tcx>,
1195 candidate_set: &mut ProjectionTyCandidateSet<'tcx>,
1197 debug!("assemble_candidates_from_object_ty(..)");
1199 let tcx = selcx.tcx();
1201 let self_ty = obligation.predicate.self_ty();
1202 let object_ty = selcx.infcx().shallow_resolve(self_ty);
1203 let data = match object_ty.kind() {
1204 ty::Dynamic(data, ..) => data,
1205 ty::Infer(ty::TyVar(_)) => {
1206 // If the self-type is an inference variable, then it MAY wind up
1207 // being an object type, so induce an ambiguity.
1208 candidate_set.mark_ambiguous();
1213 let env_predicates = data
1214 .projection_bounds()
1215 .filter(|bound| bound.item_def_id() == obligation.predicate.item_def_id)
1216 .map(|p| p.with_self_ty(tcx, object_ty).to_predicate(tcx));
1218 assemble_candidates_from_predicates(
1222 ProjectionTyCandidate::Object,
1228 #[tracing::instrument(
1230 skip(selcx, candidate_set, ctor, env_predicates, potentially_unnormalized_candidates)
1232 fn assemble_candidates_from_predicates<'cx, 'tcx>(
1233 selcx: &mut SelectionContext<'cx, 'tcx>,
1234 obligation: &ProjectionTyObligation<'tcx>,
1235 candidate_set: &mut ProjectionTyCandidateSet<'tcx>,
1236 ctor: fn(ty::PolyProjectionPredicate<'tcx>) -> ProjectionTyCandidate<'tcx>,
1237 env_predicates: impl Iterator<Item = ty::Predicate<'tcx>>,
1238 potentially_unnormalized_candidates: bool,
1240 let infcx = selcx.infcx();
1241 for predicate in env_predicates {
1243 let bound_predicate = predicate.kind();
1244 if let ty::PredicateKind::Projection(data) = predicate.kind().skip_binder() {
1245 let data = bound_predicate.rebind(data);
1246 let same_def_id = data.projection_def_id() == obligation.predicate.item_def_id;
1248 let is_match = same_def_id
1249 && infcx.probe(|_| {
1250 selcx.match_projection_projections(
1253 potentially_unnormalized_candidates,
1257 debug!(?data, ?is_match, ?same_def_id);
1260 candidate_set.push_candidate(ctor(data));
1262 if potentially_unnormalized_candidates
1263 && !obligation.predicate.has_infer_types_or_consts()
1265 // HACK: Pick the first trait def candidate for a fully
1266 // inferred predicate. This is to allow duplicates that
1267 // differ only in normalization.
1275 #[tracing::instrument(level = "debug", skip(selcx, obligation, candidate_set))]
1276 fn assemble_candidates_from_impls<'cx, 'tcx>(
1277 selcx: &mut SelectionContext<'cx, 'tcx>,
1278 obligation: &ProjectionTyObligation<'tcx>,
1279 candidate_set: &mut ProjectionTyCandidateSet<'tcx>,
1281 // If we are resolving `<T as TraitRef<...>>::Item == Type`,
1282 // start out by selecting the predicate `T as TraitRef<...>`:
1283 let poly_trait_ref = ty::Binder::dummy(obligation.predicate.trait_ref(selcx.tcx()));
1284 let trait_obligation = obligation.with(poly_trait_ref.to_poly_trait_predicate());
1285 let _ = selcx.infcx().commit_if_ok(|_| {
1286 let impl_source = match selcx.select(&trait_obligation) {
1287 Ok(Some(impl_source)) => impl_source,
1289 candidate_set.mark_ambiguous();
1293 debug!(error = ?e, "selection error");
1294 candidate_set.mark_error(e);
1299 let eligible = match &impl_source {
1300 super::ImplSource::Closure(_)
1301 | super::ImplSource::Generator(_)
1302 | super::ImplSource::FnPointer(_)
1303 | super::ImplSource::TraitAlias(_) => {
1304 debug!(?impl_source);
1307 super::ImplSource::UserDefined(impl_data) => {
1308 // We have to be careful when projecting out of an
1309 // impl because of specialization. If we are not in
1310 // codegen (i.e., projection mode is not "any"), and the
1311 // impl's type is declared as default, then we disable
1312 // projection (even if the trait ref is fully
1313 // monomorphic). In the case where trait ref is not
1314 // fully monomorphic (i.e., includes type parameters),
1315 // this is because those type parameters may
1316 // ultimately be bound to types from other crates that
1317 // may have specialized impls we can't see. In the
1318 // case where the trait ref IS fully monomorphic, this
1319 // is a policy decision that we made in the RFC in
1320 // order to preserve flexibility for the crate that
1321 // defined the specializable impl to specialize later
1322 // for existing types.
1324 // In either case, we handle this by not adding a
1325 // candidate for an impl if it contains a `default`
1328 // NOTE: This should be kept in sync with the similar code in
1329 // `rustc_ty_utils::instance::resolve_associated_item()`.
1331 assoc_ty_def(selcx, impl_data.impl_def_id, obligation.predicate.item_def_id)
1332 .map_err(|ErrorReported| ())?;
1334 if node_item.is_final() {
1335 // Non-specializable items are always projectable.
1338 // Only reveal a specializable default if we're past type-checking
1339 // and the obligation is monomorphic, otherwise passes such as
1340 // transmute checking and polymorphic MIR optimizations could
1341 // get a result which isn't correct for all monomorphizations.
1342 if obligation.param_env.reveal() == Reveal::All {
1343 // NOTE(eddyb) inference variables can resolve to parameters, so
1344 // assume `poly_trait_ref` isn't monomorphic, if it contains any.
1345 let poly_trait_ref = selcx.infcx().resolve_vars_if_possible(poly_trait_ref);
1346 !poly_trait_ref.still_further_specializable()
1349 assoc_ty = ?selcx.tcx().def_path_str(node_item.item.def_id),
1350 ?obligation.predicate,
1351 "assemble_candidates_from_impls: not eligible due to default",
1357 super::ImplSource::DiscriminantKind(..) => {
1358 // While `DiscriminantKind` is automatically implemented for every type,
1359 // the concrete discriminant may not be known yet.
1361 // Any type with multiple potential discriminant types is therefore not eligible.
1362 let self_ty = selcx.infcx().shallow_resolve(obligation.predicate.self_ty());
1364 match self_ty.kind() {
1382 | ty::GeneratorWitness(..)
1385 // Integers and floats always have `u8` as their discriminant.
1386 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(..)) => true,
1392 | ty::Placeholder(..)
1394 | ty::Error(_) => false,
1397 super::ImplSource::Pointee(..) => {
1398 // While `Pointee` is automatically implemented for every type,
1399 // the concrete metadata type may not be known yet.
1401 // Any type with multiple potential metadata types is therefore not eligible.
1402 let self_ty = selcx.infcx().shallow_resolve(obligation.predicate.self_ty());
1404 let tail = selcx.tcx().struct_tail_with_normalize(self_ty, |ty| {
1405 normalize_with_depth(
1407 obligation.param_env,
1408 obligation.cause.clone(),
1409 obligation.recursion_depth + 1,
1432 | ty::GeneratorWitness(..)
1434 // If returned by `struct_tail_without_normalization` this is a unit struct
1435 // without any fields, or not a struct, and therefore is Sized.
1437 // If returned by `struct_tail_without_normalization` this is the empty tuple.
1439 // Integers and floats are always Sized, and so have unit type metadata.
1440 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(..)) => true,
1446 | ty::Placeholder(..)
1449 if tail.has_infer_types() {
1450 candidate_set.mark_ambiguous();
1456 super::ImplSource::Param(..) => {
1457 // This case tell us nothing about the value of an
1458 // associated type. Consider:
1461 // trait SomeTrait { type Foo; }
1462 // fn foo<T:SomeTrait>(...) { }
1465 // If the user writes `<T as SomeTrait>::Foo`, then the `T
1466 // : SomeTrait` binding does not help us decide what the
1467 // type `Foo` is (at least, not more specifically than
1468 // what we already knew).
1470 // But wait, you say! What about an example like this:
1473 // fn bar<T:SomeTrait<Foo=usize>>(...) { ... }
1476 // Doesn't the `T : Sometrait<Foo=usize>` predicate help
1477 // resolve `T::Foo`? And of course it does, but in fact
1478 // that single predicate is desugared into two predicates
1479 // in the compiler: a trait predicate (`T : SomeTrait`) and a
1480 // projection. And the projection where clause is handled
1481 // in `assemble_candidates_from_param_env`.
1484 super::ImplSource::Object(_) => {
1485 // Handled by the `Object` projection candidate. See
1486 // `assemble_candidates_from_object_ty` for an explanation of
1487 // why we special case object types.
1490 super::ImplSource::AutoImpl(..)
1491 | super::ImplSource::Builtin(..)
1492 | super::ImplSource::TraitUpcasting(_)
1493 | super::ImplSource::ConstDrop(_) => {
1494 // These traits have no associated types.
1495 selcx.tcx().sess.delay_span_bug(
1496 obligation.cause.span,
1497 &format!("Cannot project an associated type from `{:?}`", impl_source),
1504 if candidate_set.push_candidate(ProjectionTyCandidate::Select(impl_source)) {
1515 fn confirm_candidate<'cx, 'tcx>(
1516 selcx: &mut SelectionContext<'cx, 'tcx>,
1517 obligation: &ProjectionTyObligation<'tcx>,
1518 candidate: ProjectionTyCandidate<'tcx>,
1519 ) -> Progress<'tcx> {
1520 debug!(?obligation, ?candidate, "confirm_candidate");
1521 let mut progress = match candidate {
1522 ProjectionTyCandidate::ParamEnv(poly_projection)
1523 | ProjectionTyCandidate::Object(poly_projection) => {
1524 confirm_param_env_candidate(selcx, obligation, poly_projection, false)
1527 ProjectionTyCandidate::TraitDef(poly_projection) => {
1528 confirm_param_env_candidate(selcx, obligation, poly_projection, true)
1531 ProjectionTyCandidate::Select(impl_source) => {
1532 confirm_select_candidate(selcx, obligation, impl_source)
1535 // When checking for cycle during evaluation, we compare predicates with
1536 // "syntactic" equality. Since normalization generally introduces a type
1537 // with new region variables, we need to resolve them to existing variables
1538 // when possible for this to work. See `auto-trait-projection-recursion.rs`
1539 // for a case where this matters.
1540 if progress.ty.has_infer_regions() {
1541 progress.ty = OpportunisticRegionResolver::new(selcx.infcx()).fold_ty(progress.ty);
1546 fn confirm_select_candidate<'cx, 'tcx>(
1547 selcx: &mut SelectionContext<'cx, 'tcx>,
1548 obligation: &ProjectionTyObligation<'tcx>,
1549 impl_source: Selection<'tcx>,
1550 ) -> Progress<'tcx> {
1552 super::ImplSource::UserDefined(data) => confirm_impl_candidate(selcx, obligation, data),
1553 super::ImplSource::Generator(data) => confirm_generator_candidate(selcx, obligation, data),
1554 super::ImplSource::Closure(data) => confirm_closure_candidate(selcx, obligation, data),
1555 super::ImplSource::FnPointer(data) => confirm_fn_pointer_candidate(selcx, obligation, data),
1556 super::ImplSource::DiscriminantKind(data) => {
1557 confirm_discriminant_kind_candidate(selcx, obligation, data)
1559 super::ImplSource::Pointee(data) => confirm_pointee_candidate(selcx, obligation, data),
1560 super::ImplSource::Object(_)
1561 | super::ImplSource::AutoImpl(..)
1562 | super::ImplSource::Param(..)
1563 | super::ImplSource::Builtin(..)
1564 | super::ImplSource::TraitUpcasting(_)
1565 | super::ImplSource::TraitAlias(..)
1566 | super::ImplSource::ConstDrop(_) => {
1567 // we don't create Select candidates with this kind of resolution
1569 obligation.cause.span,
1570 "Cannot project an associated type from `{:?}`",
1577 fn confirm_generator_candidate<'cx, 'tcx>(
1578 selcx: &mut SelectionContext<'cx, 'tcx>,
1579 obligation: &ProjectionTyObligation<'tcx>,
1580 impl_source: ImplSourceGeneratorData<'tcx, PredicateObligation<'tcx>>,
1581 ) -> Progress<'tcx> {
1582 let gen_sig = impl_source.substs.as_generator().poly_sig();
1583 let Normalized { value: gen_sig, obligations } = normalize_with_depth(
1585 obligation.param_env,
1586 obligation.cause.clone(),
1587 obligation.recursion_depth + 1,
1591 debug!(?obligation, ?gen_sig, ?obligations, "confirm_generator_candidate");
1593 let tcx = selcx.tcx();
1595 let gen_def_id = tcx.require_lang_item(LangItem::Generator, None);
1597 let predicate = super::util::generator_trait_ref_and_outputs(
1600 obligation.predicate.self_ty(),
1603 .map_bound(|(trait_ref, yield_ty, return_ty)| {
1604 let name = tcx.associated_item(obligation.predicate.item_def_id).ident.name;
1605 let ty = if name == sym::Return {
1607 } else if name == sym::Yield {
1613 ty::ProjectionPredicate {
1614 projection_ty: ty::ProjectionTy {
1615 substs: trait_ref.substs,
1616 item_def_id: obligation.predicate.item_def_id,
1622 confirm_param_env_candidate(selcx, obligation, predicate, false)
1623 .with_addl_obligations(impl_source.nested)
1624 .with_addl_obligations(obligations)
1627 fn confirm_discriminant_kind_candidate<'cx, 'tcx>(
1628 selcx: &mut SelectionContext<'cx, 'tcx>,
1629 obligation: &ProjectionTyObligation<'tcx>,
1630 _: ImplSourceDiscriminantKindData,
1631 ) -> Progress<'tcx> {
1632 let tcx = selcx.tcx();
1634 let self_ty = selcx.infcx().shallow_resolve(obligation.predicate.self_ty());
1635 // We get here from `poly_project_and_unify_type` which replaces bound vars
1636 // with placeholders
1637 debug_assert!(!self_ty.has_escaping_bound_vars());
1638 let substs = tcx.mk_substs([self_ty.into()].iter());
1640 let discriminant_def_id = tcx.require_lang_item(LangItem::Discriminant, None);
1642 let predicate = ty::ProjectionPredicate {
1643 projection_ty: ty::ProjectionTy { substs, item_def_id: discriminant_def_id },
1644 term: self_ty.discriminant_ty(tcx).into(),
1647 // We get here from `poly_project_and_unify_type` which replaces bound vars
1648 // with placeholders, so dummy is okay here.
1649 confirm_param_env_candidate(selcx, obligation, ty::Binder::dummy(predicate), false)
1652 fn confirm_pointee_candidate<'cx, 'tcx>(
1653 selcx: &mut SelectionContext<'cx, 'tcx>,
1654 obligation: &ProjectionTyObligation<'tcx>,
1655 _: ImplSourcePointeeData,
1656 ) -> Progress<'tcx> {
1657 let tcx = selcx.tcx();
1658 let self_ty = selcx.infcx().shallow_resolve(obligation.predicate.self_ty());
1660 let mut obligations = vec![];
1661 let metadata_ty = self_ty.ptr_metadata_ty(tcx, |ty| {
1662 normalize_with_depth_to(
1664 obligation.param_env,
1665 obligation.cause.clone(),
1666 obligation.recursion_depth + 1,
1672 let substs = tcx.mk_substs([self_ty.into()].iter());
1673 let metadata_def_id = tcx.require_lang_item(LangItem::Metadata, None);
1675 let predicate = ty::ProjectionPredicate {
1676 projection_ty: ty::ProjectionTy { substs, item_def_id: metadata_def_id },
1677 term: metadata_ty.into(),
1680 confirm_param_env_candidate(selcx, obligation, ty::Binder::dummy(predicate), false)
1681 .with_addl_obligations(obligations)
1684 fn confirm_fn_pointer_candidate<'cx, 'tcx>(
1685 selcx: &mut SelectionContext<'cx, 'tcx>,
1686 obligation: &ProjectionTyObligation<'tcx>,
1687 fn_pointer_impl_source: ImplSourceFnPointerData<'tcx, PredicateObligation<'tcx>>,
1688 ) -> Progress<'tcx> {
1689 let fn_type = selcx.infcx().shallow_resolve(fn_pointer_impl_source.fn_ty);
1690 let sig = fn_type.fn_sig(selcx.tcx());
1691 let Normalized { value: sig, obligations } = normalize_with_depth(
1693 obligation.param_env,
1694 obligation.cause.clone(),
1695 obligation.recursion_depth + 1,
1699 confirm_callable_candidate(selcx, obligation, sig, util::TupleArgumentsFlag::Yes)
1700 .with_addl_obligations(fn_pointer_impl_source.nested)
1701 .with_addl_obligations(obligations)
1704 fn confirm_closure_candidate<'cx, 'tcx>(
1705 selcx: &mut SelectionContext<'cx, 'tcx>,
1706 obligation: &ProjectionTyObligation<'tcx>,
1707 impl_source: ImplSourceClosureData<'tcx, PredicateObligation<'tcx>>,
1708 ) -> Progress<'tcx> {
1709 let closure_sig = impl_source.substs.as_closure().sig();
1710 let Normalized { value: closure_sig, obligations } = normalize_with_depth(
1712 obligation.param_env,
1713 obligation.cause.clone(),
1714 obligation.recursion_depth + 1,
1718 debug!(?obligation, ?closure_sig, ?obligations, "confirm_closure_candidate");
1720 confirm_callable_candidate(selcx, obligation, closure_sig, util::TupleArgumentsFlag::No)
1721 .with_addl_obligations(impl_source.nested)
1722 .with_addl_obligations(obligations)
1725 fn confirm_callable_candidate<'cx, 'tcx>(
1726 selcx: &mut SelectionContext<'cx, 'tcx>,
1727 obligation: &ProjectionTyObligation<'tcx>,
1728 fn_sig: ty::PolyFnSig<'tcx>,
1729 flag: util::TupleArgumentsFlag,
1730 ) -> Progress<'tcx> {
1731 let tcx = selcx.tcx();
1733 debug!(?obligation, ?fn_sig, "confirm_callable_candidate");
1735 let fn_once_def_id = tcx.require_lang_item(LangItem::FnOnce, None);
1736 let fn_once_output_def_id = tcx.require_lang_item(LangItem::FnOnceOutput, None);
1738 let predicate = super::util::closure_trait_ref_and_return_type(
1741 obligation.predicate.self_ty(),
1745 .map_bound(|(trait_ref, ret_type)| ty::ProjectionPredicate {
1746 projection_ty: ty::ProjectionTy {
1747 substs: trait_ref.substs,
1748 item_def_id: fn_once_output_def_id,
1750 term: ret_type.into(),
1753 confirm_param_env_candidate(selcx, obligation, predicate, true)
1756 fn confirm_param_env_candidate<'cx, 'tcx>(
1757 selcx: &mut SelectionContext<'cx, 'tcx>,
1758 obligation: &ProjectionTyObligation<'tcx>,
1759 poly_cache_entry: ty::PolyProjectionPredicate<'tcx>,
1760 potentially_unnormalized_candidate: bool,
1761 ) -> Progress<'tcx> {
1762 let infcx = selcx.infcx();
1763 let cause = &obligation.cause;
1764 let param_env = obligation.param_env;
1766 let (cache_entry, _) = infcx.replace_bound_vars_with_fresh_vars(
1768 LateBoundRegionConversionTime::HigherRankedType,
1772 let cache_projection = cache_entry.projection_ty;
1773 let mut nested_obligations = Vec::new();
1774 let obligation_projection = obligation.predicate;
1775 let obligation_projection = ensure_sufficient_stack(|| {
1776 normalize_with_depth_to(
1778 obligation.param_env,
1779 obligation.cause.clone(),
1780 obligation.recursion_depth + 1,
1781 obligation_projection,
1782 &mut nested_obligations,
1785 let cache_projection = if potentially_unnormalized_candidate {
1786 ensure_sufficient_stack(|| {
1787 normalize_with_depth_to(
1789 obligation.param_env,
1790 obligation.cause.clone(),
1791 obligation.recursion_depth + 1,
1793 &mut nested_obligations,
1800 debug!(?cache_projection, ?obligation_projection);
1802 match infcx.at(cause, param_env).eq(cache_projection, obligation_projection) {
1803 Ok(InferOk { value: _, obligations }) => {
1804 nested_obligations.extend(obligations);
1805 assoc_ty_own_obligations(selcx, obligation, &mut nested_obligations);
1806 Progress { ty: cache_entry.term.ty(), obligations: nested_obligations }
1810 "Failed to unify obligation `{:?}` with poly_projection `{:?}`: {:?}",
1811 obligation, poly_cache_entry, e,
1813 debug!("confirm_param_env_candidate: {}", msg);
1814 let err = infcx.tcx.ty_error_with_message(obligation.cause.span, &msg);
1815 Progress { ty: err, obligations: vec![] }
1820 fn confirm_impl_candidate<'cx, 'tcx>(
1821 selcx: &mut SelectionContext<'cx, 'tcx>,
1822 obligation: &ProjectionTyObligation<'tcx>,
1823 impl_impl_source: ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>>,
1824 ) -> Progress<'tcx> {
1825 let tcx = selcx.tcx();
1827 let ImplSourceUserDefinedData { impl_def_id, substs, mut nested } = impl_impl_source;
1828 let assoc_item_id = obligation.predicate.item_def_id;
1829 let trait_def_id = tcx.trait_id_of_impl(impl_def_id).unwrap();
1831 let param_env = obligation.param_env;
1832 let assoc_ty = match assoc_ty_def(selcx, impl_def_id, assoc_item_id) {
1833 Ok(assoc_ty) => assoc_ty,
1834 Err(ErrorReported) => return Progress { ty: tcx.ty_error(), obligations: nested },
1837 if !assoc_ty.item.defaultness.has_value() {
1838 // This means that the impl is missing a definition for the
1839 // associated type. This error will be reported by the type
1840 // checker method `check_impl_items_against_trait`, so here we
1841 // just return Error.
1843 "confirm_impl_candidate: no associated type {:?} for {:?}",
1844 assoc_ty.item.ident, obligation.predicate
1846 return Progress { ty: tcx.ty_error(), obligations: nested };
1848 // If we're trying to normalize `<Vec<u32> as X>::A<S>` using
1849 //`impl<T> X for Vec<T> { type A<Y> = Box<Y>; }`, then:
1851 // * `obligation.predicate.substs` is `[Vec<u32>, S]`
1852 // * `substs` is `[u32]`
1853 // * `substs` ends up as `[u32, S]`
1854 let substs = obligation.predicate.substs.rebase_onto(tcx, trait_def_id, substs);
1856 translate_substs(selcx.infcx(), param_env, impl_def_id, substs, assoc_ty.defining_node);
1857 let ty = tcx.type_of(assoc_ty.item.def_id);
1858 if substs.len() != tcx.generics_of(assoc_ty.item.def_id).count() {
1859 let err = tcx.ty_error_with_message(
1860 obligation.cause.span,
1861 "impl item and trait item have different parameter counts",
1863 Progress { ty: err, obligations: nested }
1865 assoc_ty_own_obligations(selcx, obligation, &mut nested);
1866 Progress { ty: ty.subst(tcx, substs), obligations: nested }
1870 // Get obligations corresponding to the predicates from the where-clause of the
1871 // associated type itself.
1872 // Note: `feature(generic_associated_types)` is required to write such
1873 // predicates, even for non-generic associcated types.
1874 fn assoc_ty_own_obligations<'cx, 'tcx>(
1875 selcx: &mut SelectionContext<'cx, 'tcx>,
1876 obligation: &ProjectionTyObligation<'tcx>,
1877 nested: &mut Vec<PredicateObligation<'tcx>>,
1879 let tcx = selcx.tcx();
1880 for predicate in tcx
1881 .predicates_of(obligation.predicate.item_def_id)
1882 .instantiate_own(tcx, obligation.predicate.substs)
1885 let normalized = normalize_with_depth_to(
1887 obligation.param_env,
1888 obligation.cause.clone(),
1889 obligation.recursion_depth + 1,
1893 nested.push(Obligation::with_depth(
1894 obligation.cause.clone(),
1895 obligation.recursion_depth + 1,
1896 obligation.param_env,
1902 /// Locate the definition of an associated type in the specialization hierarchy,
1903 /// starting from the given impl.
1905 /// Based on the "projection mode", this lookup may in fact only examine the
1906 /// topmost impl. See the comments for `Reveal` for more details.
1908 selcx: &SelectionContext<'_, '_>,
1910 assoc_ty_def_id: DefId,
1911 ) -> Result<specialization_graph::LeafDef, ErrorReported> {
1912 let tcx = selcx.tcx();
1913 let trait_def_id = tcx.impl_trait_ref(impl_def_id).unwrap().def_id;
1914 let trait_def = tcx.trait_def(trait_def_id);
1916 // This function may be called while we are still building the
1917 // specialization graph that is queried below (via TraitDef::ancestors()),
1918 // so, in order to avoid unnecessary infinite recursion, we manually look
1919 // for the associated item at the given impl.
1920 // If there is no such item in that impl, this function will fail with a
1921 // cycle error if the specialization graph is currently being built.
1922 if let Some(&impl_item_id) = tcx.impl_item_implementor_ids(impl_def_id).get(&assoc_ty_def_id) {
1923 let item = tcx.associated_item(impl_item_id);
1924 let impl_node = specialization_graph::Node::Impl(impl_def_id);
1925 return Ok(specialization_graph::LeafDef {
1927 defining_node: impl_node,
1928 finalizing_node: if item.defaultness.is_default() { None } else { Some(impl_node) },
1932 let ancestors = trait_def.ancestors(tcx, impl_def_id)?;
1933 if let Some(assoc_item) = ancestors.leaf_def(tcx, assoc_ty_def_id) {
1936 // This is saying that neither the trait nor
1937 // the impl contain a definition for this
1938 // associated type. Normally this situation
1939 // could only arise through a compiler bug --
1940 // if the user wrote a bad item name, it
1941 // should have failed in astconv.
1943 "No associated type `{}` for {}",
1944 tcx.item_name(assoc_ty_def_id),
1945 tcx.def_path_str(impl_def_id)
1950 crate trait ProjectionCacheKeyExt<'cx, 'tcx>: Sized {
1951 fn from_poly_projection_predicate(
1952 selcx: &mut SelectionContext<'cx, 'tcx>,
1953 predicate: ty::PolyProjectionPredicate<'tcx>,
1957 impl<'cx, 'tcx> ProjectionCacheKeyExt<'cx, 'tcx> for ProjectionCacheKey<'tcx> {
1958 fn from_poly_projection_predicate(
1959 selcx: &mut SelectionContext<'cx, 'tcx>,
1960 predicate: ty::PolyProjectionPredicate<'tcx>,
1962 let infcx = selcx.infcx();
1963 // We don't do cross-snapshot caching of obligations with escaping regions,
1964 // so there's no cache key to use
1965 predicate.no_bound_vars().map(|predicate| {
1966 ProjectionCacheKey::new(
1967 // We don't attempt to match up with a specific type-variable state
1968 // from a specific call to `opt_normalize_projection_type` - if
1969 // there's no precise match, the original cache entry is "stranded"
1971 infcx.resolve_vars_if_possible(predicate.projection_ty),