]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/project.rs
Rollup merge of #99194 - simlay:simlay/update-rust-gdbgui-gdb-args-to-gdb-cmd, r...
[rust.git] / compiler / rustc_trait_selection / src / traits / project.rs
1 //! Code for projecting associated types out of trait references.
2
3 use super::specialization_graph;
4 use super::translate_substs;
5 use super::util;
6 use super::MismatchedProjectionTypes;
7 use super::Obligation;
8 use super::ObligationCause;
9 use super::PredicateObligation;
10 use super::Selection;
11 use super::SelectionContext;
12 use super::SelectionError;
13 use super::{
14     ImplSourceClosureData, ImplSourceDiscriminantKindData, ImplSourceFnPointerData,
15     ImplSourceGeneratorData, ImplSourcePointeeData, ImplSourceUserDefinedData,
16 };
17 use super::{Normalized, NormalizedTy, ProjectionCacheEntry, ProjectionCacheKey};
18
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;
37
38 use std::collections::BTreeMap;
39
40 pub use rustc_middle::traits::Reveal;
41
42 pub type PolyProjectionObligation<'tcx> = Obligation<'tcx, ty::PolyProjectionPredicate<'tcx>>;
43
44 pub type ProjectionObligation<'tcx> = Obligation<'tcx, ty::ProjectionPredicate<'tcx>>;
45
46 pub type ProjectionTyObligation<'tcx> = Obligation<'tcx, ty::ProjectionTy<'tcx>>;
47
48 pub(super) struct InProgress;
49
50 /// When attempting to resolve `<T as TraitRef>::Name` ...
51 #[derive(Debug)]
52 pub enum ProjectionError<'tcx> {
53     /// ...we found multiple sources of information and couldn't resolve the ambiguity.
54     TooManyCandidates,
55
56     /// ...an error occurred matching `T : TraitRef`
57     TraitSelectionError(SelectionError<'tcx>),
58 }
59
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>),
64
65     /// From the definition of `Trait` when you have something like <<A as Trait>::B as Trait2>::C
66     TraitDef(ty::PolyProjectionPredicate<'tcx>),
67
68     /// Bounds specified on an object type
69     Object(ty::PolyProjectionPredicate<'tcx>),
70
71     /// From an "impl" (or a "pseudo-impl" returned by select)
72     Select(Selection<'tcx>),
73
74     ImplTraitInTrait(ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>>),
75 }
76
77 enum ProjectionCandidateSet<'tcx> {
78     None,
79     Single(ProjectionCandidate<'tcx>),
80     Ambiguous,
81     Error(SelectionError<'tcx>),
82 }
83
84 impl<'tcx> ProjectionCandidateSet<'tcx> {
85     fn mark_ambiguous(&mut self) {
86         *self = ProjectionCandidateSet::Ambiguous;
87     }
88
89     fn mark_error(&mut self, err: SelectionError<'tcx>) {
90         *self = ProjectionCandidateSet::Error(err);
91     }
92
93     // Returns true if the push was successful, or false if the candidate
94     // was discarded -- this could be because of ambiguity, or because
95     // a higher-priority candidate is already there.
96     fn push_candidate(&mut self, candidate: ProjectionCandidate<'tcx>) -> bool {
97         use self::ProjectionCandidate::*;
98         use self::ProjectionCandidateSet::*;
99
100         // This wacky variable is just used to try and
101         // make code readable and avoid confusing paths.
102         // It is assigned a "value" of `()` only on those
103         // paths in which we wish to convert `*self` to
104         // ambiguous (and return false, because the candidate
105         // was not used). On other paths, it is not assigned,
106         // and hence if those paths *could* reach the code that
107         // comes after the match, this fn would not compile.
108         let convert_to_ambiguous;
109
110         match self {
111             None => {
112                 *self = Single(candidate);
113                 return true;
114             }
115
116             Single(current) => {
117                 // Duplicates can happen inside ParamEnv. In the case, we
118                 // perform a lazy deduplication.
119                 if current == &candidate {
120                     return false;
121                 }
122
123                 // Prefer where-clauses. As in select, if there are multiple
124                 // candidates, we prefer where-clause candidates over impls.  This
125                 // may seem a bit surprising, since impls are the source of
126                 // "truth" in some sense, but in fact some of the impls that SEEM
127                 // applicable are not, because of nested obligations. Where
128                 // clauses are the safer choice. See the comment on
129                 // `select::SelectionCandidate` and #21974 for more details.
130                 match (current, candidate) {
131                     (ParamEnv(..), ParamEnv(..)) => convert_to_ambiguous = (),
132                     (ParamEnv(..), _) => return false,
133                     (_, ParamEnv(..)) => unreachable!(),
134                     (_, _) => convert_to_ambiguous = (),
135                 }
136             }
137
138             Ambiguous | Error(..) => {
139                 return false;
140             }
141         }
142
143         // We only ever get here when we moved from a single candidate
144         // to ambiguous.
145         let () = convert_to_ambiguous;
146         *self = Ambiguous;
147         false
148     }
149 }
150
151 /// States returned from `poly_project_and_unify_type`. Takes the place
152 /// of the old return type, which was:
153 /// ```ignore (not-rust)
154 /// Result<
155 ///     Result<Option<Vec<PredicateObligation<'tcx>>>, InProgress>,
156 ///     MismatchedProjectionTypes<'tcx>,
157 /// >
158 /// ```
159 pub(super) enum ProjectAndUnifyResult<'tcx> {
160     /// The projection bound holds subject to the given obligations. If the
161     /// projection cannot be normalized because the required trait bound does
162     /// not hold, this is returned, with `obligations` being a predicate that
163     /// cannot be proven.
164     Holds(Vec<PredicateObligation<'tcx>>),
165     /// The projection cannot be normalized due to ambiguity. Resolving some
166     /// inference variables in the projection may fix this.
167     FailedNormalization,
168     /// The project cannot be normalized because `poly_project_and_unify_type`
169     /// is called recursively while normalizing the same projection.
170     Recursive,
171     // the projection can be normalized, but is not equal to the expected type.
172     // Returns the type error that arose from the mismatch.
173     MismatchedProjectionTypes(MismatchedProjectionTypes<'tcx>),
174 }
175
176 /// Evaluates constraints of the form:
177 /// ```ignore (not-rust)
178 /// for<...> <T as Trait>::U == V
179 /// ```
180 /// If successful, this may result in additional obligations. Also returns
181 /// the projection cache key used to track these additional obligations.
182 #[instrument(level = "debug", skip(selcx))]
183 pub(super) fn poly_project_and_unify_type<'cx, 'tcx>(
184     selcx: &mut SelectionContext<'cx, 'tcx>,
185     obligation: &PolyProjectionObligation<'tcx>,
186 ) -> ProjectAndUnifyResult<'tcx> {
187     let infcx = selcx.infcx();
188     let r = infcx.commit_if_ok(|_snapshot| {
189         let old_universe = infcx.universe();
190         let placeholder_predicate =
191             infcx.replace_bound_vars_with_placeholders(obligation.predicate);
192         let new_universe = infcx.universe();
193
194         let placeholder_obligation = obligation.with(placeholder_predicate);
195         match project_and_unify_type(selcx, &placeholder_obligation) {
196             ProjectAndUnifyResult::MismatchedProjectionTypes(e) => Err(e),
197             ProjectAndUnifyResult::Holds(obligations)
198                 if old_universe != new_universe
199                     && selcx.tcx().features().generic_associated_types_extended =>
200             {
201                 // If the `generic_associated_types_extended` feature is active, then we ignore any
202                 // obligations references lifetimes from any universe greater than or equal to the
203                 // universe just created. Otherwise, we can end up with something like `for<'a> I: 'a`,
204                 // which isn't quite what we want. Ideally, we want either an implied
205                 // `for<'a where I: 'a> I: 'a` or we want to "lazily" check these hold when we
206                 // substitute concrete regions. There is design work to be done here; until then,
207                 // however, this allows experimenting potential GAT features without running into
208                 // well-formedness issues.
209                 let new_obligations = obligations
210                     .into_iter()
211                     .filter(|obligation| {
212                         let mut visitor = MaxUniverse::new();
213                         obligation.predicate.visit_with(&mut visitor);
214                         visitor.max_universe() < new_universe
215                     })
216                     .collect();
217                 Ok(ProjectAndUnifyResult::Holds(new_obligations))
218             }
219             other => Ok(other),
220         }
221     });
222
223     match r {
224         Ok(inner) => inner,
225         Err(err) => ProjectAndUnifyResult::MismatchedProjectionTypes(err),
226     }
227 }
228
229 /// Evaluates constraints of the form:
230 /// ```ignore (not-rust)
231 /// <T as Trait>::U == V
232 /// ```
233 /// If successful, this may result in additional obligations.
234 ///
235 /// See [poly_project_and_unify_type] for an explanation of the return value.
236 #[instrument(level = "debug", skip(selcx))]
237 fn project_and_unify_type<'cx, 'tcx>(
238     selcx: &mut SelectionContext<'cx, 'tcx>,
239     obligation: &ProjectionObligation<'tcx>,
240 ) -> ProjectAndUnifyResult<'tcx> {
241     let mut obligations = vec![];
242
243     let infcx = selcx.infcx();
244     let normalized = match opt_normalize_projection_type(
245         selcx,
246         obligation.param_env,
247         obligation.predicate.projection_ty,
248         obligation.cause.clone(),
249         obligation.recursion_depth,
250         &mut obligations,
251     ) {
252         Ok(Some(n)) => n,
253         Ok(None) => return ProjectAndUnifyResult::FailedNormalization,
254         Err(InProgress) => return ProjectAndUnifyResult::Recursive,
255     };
256     debug!(?normalized, ?obligations, "project_and_unify_type result");
257     let actual = obligation.predicate.term;
258     // For an example where this is neccessary see src/test/ui/impl-trait/nested-return-type2.rs
259     // This allows users to omit re-mentioning all bounds on an associated type and just use an
260     // `impl Trait` for the assoc type to add more bounds.
261     let InferOk { value: actual, obligations: new } =
262         selcx.infcx().replace_opaque_types_with_inference_vars(
263             actual,
264             obligation.cause.body_id,
265             obligation.cause.span,
266             obligation.param_env,
267         );
268     obligations.extend(new);
269
270     match infcx.at(&obligation.cause, obligation.param_env).eq(normalized, actual) {
271         Ok(InferOk { obligations: inferred_obligations, value: () }) => {
272             obligations.extend(inferred_obligations);
273             ProjectAndUnifyResult::Holds(obligations)
274         }
275         Err(err) => {
276             debug!("equating types encountered error {:?}", err);
277             ProjectAndUnifyResult::MismatchedProjectionTypes(MismatchedProjectionTypes { err })
278         }
279     }
280 }
281
282 /// Normalizes any associated type projections in `value`, replacing
283 /// them with a fully resolved type where possible. The return value
284 /// combines the normalized result and any additional obligations that
285 /// were incurred as result.
286 pub fn normalize<'a, 'b, 'tcx, T>(
287     selcx: &'a mut SelectionContext<'b, 'tcx>,
288     param_env: ty::ParamEnv<'tcx>,
289     cause: ObligationCause<'tcx>,
290     value: T,
291 ) -> Normalized<'tcx, T>
292 where
293     T: TypeFoldable<'tcx>,
294 {
295     let mut obligations = Vec::new();
296     let value = normalize_to(selcx, param_env, cause, value, &mut obligations);
297     Normalized { value, obligations }
298 }
299
300 pub fn normalize_to<'a, 'b, 'tcx, T>(
301     selcx: &'a mut SelectionContext<'b, 'tcx>,
302     param_env: ty::ParamEnv<'tcx>,
303     cause: ObligationCause<'tcx>,
304     value: T,
305     obligations: &mut Vec<PredicateObligation<'tcx>>,
306 ) -> T
307 where
308     T: TypeFoldable<'tcx>,
309 {
310     normalize_with_depth_to(selcx, param_env, cause, 0, value, obligations)
311 }
312
313 /// As `normalize`, but with a custom depth.
314 pub fn normalize_with_depth<'a, 'b, 'tcx, T>(
315     selcx: &'a mut SelectionContext<'b, 'tcx>,
316     param_env: ty::ParamEnv<'tcx>,
317     cause: ObligationCause<'tcx>,
318     depth: usize,
319     value: T,
320 ) -> Normalized<'tcx, T>
321 where
322     T: TypeFoldable<'tcx>,
323 {
324     let mut obligations = Vec::new();
325     let value = normalize_with_depth_to(selcx, param_env, cause, depth, value, &mut obligations);
326     Normalized { value, obligations }
327 }
328
329 #[instrument(level = "info", skip(selcx, param_env, cause, obligations))]
330 pub fn normalize_with_depth_to<'a, 'b, 'tcx, T>(
331     selcx: &'a mut SelectionContext<'b, 'tcx>,
332     param_env: ty::ParamEnv<'tcx>,
333     cause: ObligationCause<'tcx>,
334     depth: usize,
335     value: T,
336     obligations: &mut Vec<PredicateObligation<'tcx>>,
337 ) -> T
338 where
339     T: TypeFoldable<'tcx>,
340 {
341     debug!(obligations.len = obligations.len());
342     let mut normalizer = AssocTypeNormalizer::new(selcx, param_env, cause, depth, obligations);
343     let result = ensure_sufficient_stack(|| normalizer.fold(value));
344     debug!(?result, obligations.len = normalizer.obligations.len());
345     debug!(?normalizer.obligations,);
346     result
347 }
348
349 #[instrument(level = "info", skip(selcx, param_env, cause, obligations))]
350 pub fn try_normalize_with_depth_to<'a, 'b, 'tcx, T>(
351     selcx: &'a mut SelectionContext<'b, 'tcx>,
352     param_env: ty::ParamEnv<'tcx>,
353     cause: ObligationCause<'tcx>,
354     depth: usize,
355     value: T,
356     obligations: &mut Vec<PredicateObligation<'tcx>>,
357 ) -> T
358 where
359     T: TypeFoldable<'tcx>,
360 {
361     debug!(obligations.len = obligations.len());
362     let mut normalizer = AssocTypeNormalizer::new_without_eager_inference_replacement(
363         selcx,
364         param_env,
365         cause,
366         depth,
367         obligations,
368     );
369     let result = ensure_sufficient_stack(|| normalizer.fold(value));
370     debug!(?result, obligations.len = normalizer.obligations.len());
371     debug!(?normalizer.obligations,);
372     result
373 }
374
375 pub(crate) fn needs_normalization<'tcx, T: TypeVisitable<'tcx>>(value: &T, reveal: Reveal) -> bool {
376     match reveal {
377         Reveal::UserFacing => value
378             .has_type_flags(ty::TypeFlags::HAS_TY_PROJECTION | ty::TypeFlags::HAS_CT_PROJECTION),
379         Reveal::All => value.has_type_flags(
380             ty::TypeFlags::HAS_TY_PROJECTION
381                 | ty::TypeFlags::HAS_TY_OPAQUE
382                 | ty::TypeFlags::HAS_CT_PROJECTION,
383         ),
384     }
385 }
386
387 struct AssocTypeNormalizer<'a, 'b, 'tcx> {
388     selcx: &'a mut SelectionContext<'b, 'tcx>,
389     param_env: ty::ParamEnv<'tcx>,
390     cause: ObligationCause<'tcx>,
391     obligations: &'a mut Vec<PredicateObligation<'tcx>>,
392     depth: usize,
393     universes: Vec<Option<ty::UniverseIndex>>,
394     /// If true, when a projection is unable to be completed, an inference
395     /// variable will be created and an obligation registered to project to that
396     /// inference variable. Also, constants will be eagerly evaluated.
397     eager_inference_replacement: bool,
398 }
399
400 impl<'a, 'b, 'tcx> AssocTypeNormalizer<'a, 'b, 'tcx> {
401     fn new(
402         selcx: &'a mut SelectionContext<'b, 'tcx>,
403         param_env: ty::ParamEnv<'tcx>,
404         cause: ObligationCause<'tcx>,
405         depth: usize,
406         obligations: &'a mut Vec<PredicateObligation<'tcx>>,
407     ) -> AssocTypeNormalizer<'a, 'b, 'tcx> {
408         AssocTypeNormalizer {
409             selcx,
410             param_env,
411             cause,
412             obligations,
413             depth,
414             universes: vec![],
415             eager_inference_replacement: true,
416         }
417     }
418
419     fn new_without_eager_inference_replacement(
420         selcx: &'a mut SelectionContext<'b, 'tcx>,
421         param_env: ty::ParamEnv<'tcx>,
422         cause: ObligationCause<'tcx>,
423         depth: usize,
424         obligations: &'a mut Vec<PredicateObligation<'tcx>>,
425     ) -> AssocTypeNormalizer<'a, 'b, 'tcx> {
426         AssocTypeNormalizer {
427             selcx,
428             param_env,
429             cause,
430             obligations,
431             depth,
432             universes: vec![],
433             eager_inference_replacement: false,
434         }
435     }
436
437     fn fold<T: TypeFoldable<'tcx>>(&mut self, value: T) -> T {
438         let value = self.selcx.infcx().resolve_vars_if_possible(value);
439         debug!(?value);
440
441         assert!(
442             !value.has_escaping_bound_vars(),
443             "Normalizing {:?} without wrapping in a `Binder`",
444             value
445         );
446
447         if !needs_normalization(&value, self.param_env.reveal()) {
448             value
449         } else {
450             value.fold_with(self)
451         }
452     }
453 }
454
455 impl<'a, 'b, 'tcx> TypeFolder<'tcx> for AssocTypeNormalizer<'a, 'b, 'tcx> {
456     fn tcx<'c>(&'c self) -> TyCtxt<'tcx> {
457         self.selcx.tcx()
458     }
459
460     fn fold_binder<T: TypeFoldable<'tcx>>(
461         &mut self,
462         t: ty::Binder<'tcx, T>,
463     ) -> ty::Binder<'tcx, T> {
464         self.universes.push(None);
465         let t = t.super_fold_with(self);
466         self.universes.pop();
467         t
468     }
469
470     fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
471         if !needs_normalization(&ty, self.param_env.reveal()) {
472             return ty;
473         }
474
475         // We try to be a little clever here as a performance optimization in
476         // cases where there are nested projections under binders.
477         // For example:
478         // ```
479         // for<'a> fn(<T as Foo>::One<'a, Box<dyn Bar<'a, Item=<T as Foo>::Two<'a>>>>)
480         // ```
481         // We normalize the substs on the projection before the projecting, but
482         // if we're naive, we'll
483         //   replace bound vars on inner, project inner, replace placeholders on inner,
484         //   replace bound vars on outer, project outer, replace placeholders on outer
485         //
486         // However, if we're a bit more clever, we can replace the bound vars
487         // on the entire type before normalizing nested projections, meaning we
488         //   replace bound vars on outer, project inner,
489         //   project outer, replace placeholders on outer
490         //
491         // This is possible because the inner `'a` will already be a placeholder
492         // when we need to normalize the inner projection
493         //
494         // On the other hand, this does add a bit of complexity, since we only
495         // replace bound vars if the current type is a `Projection` and we need
496         // to make sure we don't forget to fold the substs regardless.
497
498         match *ty.kind() {
499             // This is really important. While we *can* handle this, this has
500             // severe performance implications for large opaque types with
501             // late-bound regions. See `issue-88862` benchmark.
502             ty::Opaque(def_id, substs) => {
503                 // Only normalize `impl Trait` outside of type inference, usually in codegen.
504                 match self.param_env.reveal() {
505                     Reveal::UserFacing => ty.super_fold_with(self),
506
507                     Reveal::All => {
508                         let recursion_limit = self.tcx().recursion_limit();
509                         if !recursion_limit.value_within_limit(self.depth) {
510                             let obligation = Obligation::with_depth(
511                                 self.cause.clone(),
512                                 recursion_limit.0,
513                                 self.param_env,
514                                 ty,
515                             );
516                             self.selcx.infcx().err_ctxt().report_overflow_error(&obligation, true);
517                         }
518
519                         let substs = substs.fold_with(self);
520                         let generic_ty = self.tcx().bound_type_of(def_id);
521                         let concrete_ty = generic_ty.subst(self.tcx(), substs);
522                         self.depth += 1;
523                         let folded_ty = self.fold_ty(concrete_ty);
524                         self.depth -= 1;
525                         folded_ty
526                     }
527                 }
528             }
529
530             ty::Projection(data) if !data.has_escaping_bound_vars() => {
531                 // This branch is *mostly* just an optimization: when we don't
532                 // have escaping bound vars, we don't need to replace them with
533                 // placeholders (see branch below). *Also*, we know that we can
534                 // register an obligation to *later* project, since we know
535                 // there won't be bound vars there.
536                 let data = data.fold_with(self);
537                 let normalized_ty = if self.eager_inference_replacement {
538                     normalize_projection_type(
539                         self.selcx,
540                         self.param_env,
541                         data,
542                         self.cause.clone(),
543                         self.depth,
544                         &mut self.obligations,
545                     )
546                 } else {
547                     opt_normalize_projection_type(
548                         self.selcx,
549                         self.param_env,
550                         data,
551                         self.cause.clone(),
552                         self.depth,
553                         &mut self.obligations,
554                     )
555                     .ok()
556                     .flatten()
557                     .unwrap_or_else(|| ty.super_fold_with(self).into())
558                 };
559                 // For cases like #95134 we would like to catch overflows early
560                 // otherwise they slip away away and cause ICE.
561                 let recursion_limit = self.tcx().recursion_limit();
562                 if !recursion_limit.value_within_limit(self.depth)
563                     // HACK: Don't overflow when running cargo doc see #100991
564                     && !self.tcx().sess.opts.actually_rustdoc
565                 {
566                     let obligation = Obligation::with_depth(
567                         self.cause.clone(),
568                         recursion_limit.0,
569                         self.param_env,
570                         ty,
571                     );
572                     self.selcx.infcx().err_ctxt().report_overflow_error(&obligation, true);
573                 }
574                 debug!(
575                     ?self.depth,
576                     ?ty,
577                     ?normalized_ty,
578                     obligations.len = ?self.obligations.len(),
579                     "AssocTypeNormalizer: normalized type"
580                 );
581                 normalized_ty.ty().unwrap()
582             }
583
584             ty::Projection(data) => {
585                 // If there are escaping bound vars, we temporarily replace the
586                 // bound vars with placeholders. Note though, that in the case
587                 // that we still can't project for whatever reason (e.g. self
588                 // type isn't known enough), we *can't* register an obligation
589                 // and return an inference variable (since then that obligation
590                 // would have bound vars and that's a can of worms). Instead,
591                 // we just give up and fall back to pretending like we never tried!
592                 //
593                 // Note: this isn't necessarily the final approach here; we may
594                 // want to figure out how to register obligations with escaping vars
595                 // or handle this some other way.
596
597                 let infcx = self.selcx.infcx();
598                 let (data, mapped_regions, mapped_types, mapped_consts) =
599                     BoundVarReplacer::replace_bound_vars(infcx, &mut self.universes, data);
600                 let data = data.fold_with(self);
601                 let normalized_ty = opt_normalize_projection_type(
602                     self.selcx,
603                     self.param_env,
604                     data,
605                     self.cause.clone(),
606                     self.depth,
607                     &mut self.obligations,
608                 )
609                 .ok()
610                 .flatten()
611                 .map(|term| term.ty().unwrap())
612                 .map(|normalized_ty| {
613                     PlaceholderReplacer::replace_placeholders(
614                         infcx,
615                         mapped_regions,
616                         mapped_types,
617                         mapped_consts,
618                         &self.universes,
619                         normalized_ty,
620                     )
621                 })
622                 .unwrap_or_else(|| ty.super_fold_with(self));
623
624                 debug!(
625                     ?self.depth,
626                     ?ty,
627                     ?normalized_ty,
628                     obligations.len = ?self.obligations.len(),
629                     "AssocTypeNormalizer: normalized type"
630                 );
631                 normalized_ty
632             }
633
634             _ => ty.super_fold_with(self),
635         }
636     }
637
638     #[instrument(skip(self), level = "debug")]
639     fn fold_const(&mut self, constant: ty::Const<'tcx>) -> ty::Const<'tcx> {
640         let tcx = self.selcx.tcx();
641         if tcx.lazy_normalization() {
642             constant
643         } else {
644             let constant = constant.super_fold_with(self);
645             debug!(?constant, ?self.param_env);
646             with_replaced_escaping_bound_vars(
647                 self.selcx.infcx(),
648                 &mut self.universes,
649                 constant,
650                 |constant| constant.eval(tcx, self.param_env),
651             )
652         }
653     }
654
655     #[inline]
656     fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
657         if p.allow_normalization() && needs_normalization(&p, self.param_env.reveal()) {
658             p.super_fold_with(self)
659         } else {
660             p
661         }
662     }
663 }
664
665 pub struct BoundVarReplacer<'me, 'tcx> {
666     infcx: &'me InferCtxt<'tcx>,
667     // These three maps track the bound variable that were replaced by placeholders. It might be
668     // nice to remove these since we already have the `kind` in the placeholder; we really just need
669     // the `var` (but we *could* bring that into scope if we were to track them as we pass them).
670     mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
671     mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy>,
672     mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
673     // The current depth relative to *this* folding, *not* the entire normalization. In other words,
674     // the depth of binders we've passed here.
675     current_index: ty::DebruijnIndex,
676     // The `UniverseIndex` of the binding levels above us. These are optional, since we are lazy:
677     // we don't actually create a universe until we see a bound var we have to replace.
678     universe_indices: &'me mut Vec<Option<ty::UniverseIndex>>,
679 }
680
681 /// Executes `f` on `value` after replacing all escaping bound variables with placeholders
682 /// and then replaces these placeholders with the original bound variables in the result.
683 ///
684 /// In most places, bound variables should be replaced right when entering a binder, making
685 /// this function unnecessary. However, normalization currently does not do that, so we have
686 /// to do this lazily.
687 ///
688 /// You should not add any additional uses of this function, at least not without first
689 /// discussing it with t-types.
690 ///
691 /// FIXME(@lcnr): We may even consider experimenting with eagerly replacing bound vars during
692 /// normalization as well, at which point this function will be unnecessary and can be removed.
693 pub fn with_replaced_escaping_bound_vars<'a, 'tcx, T: TypeFoldable<'tcx>, R: TypeFoldable<'tcx>>(
694     infcx: &'a InferCtxt<'tcx>,
695     universe_indices: &'a mut Vec<Option<ty::UniverseIndex>>,
696     value: T,
697     f: impl FnOnce(T) -> R,
698 ) -> R {
699     if value.has_escaping_bound_vars() {
700         let (value, mapped_regions, mapped_types, mapped_consts) =
701             BoundVarReplacer::replace_bound_vars(infcx, universe_indices, value);
702         let result = f(value);
703         PlaceholderReplacer::replace_placeholders(
704             infcx,
705             mapped_regions,
706             mapped_types,
707             mapped_consts,
708             universe_indices,
709             result,
710         )
711     } else {
712         f(value)
713     }
714 }
715
716 impl<'me, 'tcx> BoundVarReplacer<'me, 'tcx> {
717     /// Returns `Some` if we *were* able to replace bound vars. If there are any bound vars that
718     /// use a binding level above `universe_indices.len()`, we fail.
719     pub fn replace_bound_vars<T: TypeFoldable<'tcx>>(
720         infcx: &'me InferCtxt<'tcx>,
721         universe_indices: &'me mut Vec<Option<ty::UniverseIndex>>,
722         value: T,
723     ) -> (
724         T,
725         BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
726         BTreeMap<ty::PlaceholderType, ty::BoundTy>,
727         BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
728     ) {
729         let mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion> = BTreeMap::new();
730         let mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy> = BTreeMap::new();
731         let mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar> = BTreeMap::new();
732
733         let mut replacer = BoundVarReplacer {
734             infcx,
735             mapped_regions,
736             mapped_types,
737             mapped_consts,
738             current_index: ty::INNERMOST,
739             universe_indices,
740         };
741
742         let value = value.fold_with(&mut replacer);
743
744         (value, replacer.mapped_regions, replacer.mapped_types, replacer.mapped_consts)
745     }
746
747     fn universe_for(&mut self, debruijn: ty::DebruijnIndex) -> ty::UniverseIndex {
748         let infcx = self.infcx;
749         let index =
750             self.universe_indices.len() + self.current_index.as_usize() - debruijn.as_usize() - 1;
751         let universe = self.universe_indices[index].unwrap_or_else(|| {
752             for i in self.universe_indices.iter_mut().take(index + 1) {
753                 *i = i.or_else(|| Some(infcx.create_next_universe()))
754             }
755             self.universe_indices[index].unwrap()
756         });
757         universe
758     }
759 }
760
761 impl<'tcx> TypeFolder<'tcx> for BoundVarReplacer<'_, 'tcx> {
762     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
763         self.infcx.tcx
764     }
765
766     fn fold_binder<T: TypeFoldable<'tcx>>(
767         &mut self,
768         t: ty::Binder<'tcx, T>,
769     ) -> ty::Binder<'tcx, T> {
770         self.current_index.shift_in(1);
771         let t = t.super_fold_with(self);
772         self.current_index.shift_out(1);
773         t
774     }
775
776     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
777         match *r {
778             ty::ReLateBound(debruijn, _)
779                 if debruijn.as_usize() + 1
780                     > self.current_index.as_usize() + self.universe_indices.len() =>
781             {
782                 bug!("Bound vars outside of `self.universe_indices`");
783             }
784             ty::ReLateBound(debruijn, br) if debruijn >= self.current_index => {
785                 let universe = self.universe_for(debruijn);
786                 let p = ty::PlaceholderRegion { universe, name: br.kind };
787                 self.mapped_regions.insert(p, br);
788                 self.infcx.tcx.mk_region(ty::RePlaceholder(p))
789             }
790             _ => r,
791         }
792     }
793
794     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
795         match *t.kind() {
796             ty::Bound(debruijn, _)
797                 if debruijn.as_usize() + 1
798                     > self.current_index.as_usize() + self.universe_indices.len() =>
799             {
800                 bug!("Bound vars outside of `self.universe_indices`");
801             }
802             ty::Bound(debruijn, bound_ty) if debruijn >= self.current_index => {
803                 let universe = self.universe_for(debruijn);
804                 let p = ty::PlaceholderType { universe, name: bound_ty.var };
805                 self.mapped_types.insert(p, bound_ty);
806                 self.infcx.tcx.mk_ty(ty::Placeholder(p))
807             }
808             _ if t.has_vars_bound_at_or_above(self.current_index) => t.super_fold_with(self),
809             _ => t,
810         }
811     }
812
813     fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
814         match ct.kind() {
815             ty::ConstKind::Bound(debruijn, _)
816                 if debruijn.as_usize() + 1
817                     > self.current_index.as_usize() + self.universe_indices.len() =>
818             {
819                 bug!("Bound vars outside of `self.universe_indices`");
820             }
821             ty::ConstKind::Bound(debruijn, bound_const) if debruijn >= self.current_index => {
822                 let universe = self.universe_for(debruijn);
823                 let p = ty::PlaceholderConst { universe, name: bound_const };
824                 self.mapped_consts.insert(p, bound_const);
825                 self.infcx
826                     .tcx
827                     .mk_const(ty::ConstS { kind: ty::ConstKind::Placeholder(p), ty: ct.ty() })
828             }
829             _ => ct.super_fold_with(self),
830         }
831     }
832
833     fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
834         if p.has_vars_bound_at_or_above(self.current_index) { p.super_fold_with(self) } else { p }
835     }
836 }
837
838 // The inverse of `BoundVarReplacer`: replaces placeholders with the bound vars from which they came.
839 pub struct PlaceholderReplacer<'me, 'tcx> {
840     infcx: &'me InferCtxt<'tcx>,
841     mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
842     mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy>,
843     mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
844     universe_indices: &'me [Option<ty::UniverseIndex>],
845     current_index: ty::DebruijnIndex,
846 }
847
848 impl<'me, 'tcx> PlaceholderReplacer<'me, 'tcx> {
849     pub fn replace_placeholders<T: TypeFoldable<'tcx>>(
850         infcx: &'me InferCtxt<'tcx>,
851         mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>,
852         mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy>,
853         mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>,
854         universe_indices: &'me [Option<ty::UniverseIndex>],
855         value: T,
856     ) -> T {
857         let mut replacer = PlaceholderReplacer {
858             infcx,
859             mapped_regions,
860             mapped_types,
861             mapped_consts,
862             universe_indices,
863             current_index: ty::INNERMOST,
864         };
865         value.fold_with(&mut replacer)
866     }
867 }
868
869 impl<'tcx> TypeFolder<'tcx> for PlaceholderReplacer<'_, 'tcx> {
870     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
871         self.infcx.tcx
872     }
873
874     fn fold_binder<T: TypeFoldable<'tcx>>(
875         &mut self,
876         t: ty::Binder<'tcx, T>,
877     ) -> ty::Binder<'tcx, T> {
878         if !t.has_placeholders() && !t.has_infer_regions() {
879             return t;
880         }
881         self.current_index.shift_in(1);
882         let t = t.super_fold_with(self);
883         self.current_index.shift_out(1);
884         t
885     }
886
887     fn fold_region(&mut self, r0: ty::Region<'tcx>) -> ty::Region<'tcx> {
888         let r1 = match *r0 {
889             ty::ReVar(_) => self
890                 .infcx
891                 .inner
892                 .borrow_mut()
893                 .unwrap_region_constraints()
894                 .opportunistic_resolve_region(self.infcx.tcx, r0),
895             _ => r0,
896         };
897
898         let r2 = match *r1 {
899             ty::RePlaceholder(p) => {
900                 let replace_var = self.mapped_regions.get(&p);
901                 match replace_var {
902                     Some(replace_var) => {
903                         let index = self
904                             .universe_indices
905                             .iter()
906                             .position(|u| matches!(u, Some(pu) if *pu == p.universe))
907                             .unwrap_or_else(|| bug!("Unexpected placeholder universe."));
908                         let db = ty::DebruijnIndex::from_usize(
909                             self.universe_indices.len() - index + self.current_index.as_usize() - 1,
910                         );
911                         self.tcx().mk_region(ty::ReLateBound(db, *replace_var))
912                     }
913                     None => r1,
914                 }
915             }
916             _ => r1,
917         };
918
919         debug!(?r0, ?r1, ?r2, "fold_region");
920
921         r2
922     }
923
924     fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
925         match *ty.kind() {
926             ty::Placeholder(p) => {
927                 let replace_var = self.mapped_types.get(&p);
928                 match replace_var {
929                     Some(replace_var) => {
930                         let index = self
931                             .universe_indices
932                             .iter()
933                             .position(|u| matches!(u, Some(pu) if *pu == p.universe))
934                             .unwrap_or_else(|| bug!("Unexpected placeholder universe."));
935                         let db = ty::DebruijnIndex::from_usize(
936                             self.universe_indices.len() - index + self.current_index.as_usize() - 1,
937                         );
938                         self.tcx().mk_ty(ty::Bound(db, *replace_var))
939                     }
940                     None => ty,
941                 }
942             }
943
944             _ if ty.has_placeholders() || ty.has_infer_regions() => ty.super_fold_with(self),
945             _ => ty,
946         }
947     }
948
949     fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
950         if let ty::ConstKind::Placeholder(p) = ct.kind() {
951             let replace_var = self.mapped_consts.get(&p);
952             match replace_var {
953                 Some(replace_var) => {
954                     let index = self
955                         .universe_indices
956                         .iter()
957                         .position(|u| matches!(u, Some(pu) if *pu == p.universe))
958                         .unwrap_or_else(|| bug!("Unexpected placeholder universe."));
959                     let db = ty::DebruijnIndex::from_usize(
960                         self.universe_indices.len() - index + self.current_index.as_usize() - 1,
961                     );
962                     self.tcx().mk_const(ty::ConstS {
963                         kind: ty::ConstKind::Bound(db, *replace_var),
964                         ty: ct.ty(),
965                     })
966                 }
967                 None => ct,
968             }
969         } else {
970             ct.super_fold_with(self)
971         }
972     }
973 }
974
975 /// The guts of `normalize`: normalize a specific projection like `<T
976 /// as Trait>::Item`. The result is always a type (and possibly
977 /// additional obligations). If ambiguity arises, which implies that
978 /// there are unresolved type variables in the projection, we will
979 /// substitute a fresh type variable `$X` and generate a new
980 /// obligation `<T as Trait>::Item == $X` for later.
981 pub fn normalize_projection_type<'a, 'b, 'tcx>(
982     selcx: &'a mut SelectionContext<'b, 'tcx>,
983     param_env: ty::ParamEnv<'tcx>,
984     projection_ty: ty::ProjectionTy<'tcx>,
985     cause: ObligationCause<'tcx>,
986     depth: usize,
987     obligations: &mut Vec<PredicateObligation<'tcx>>,
988 ) -> Term<'tcx> {
989     opt_normalize_projection_type(
990         selcx,
991         param_env,
992         projection_ty,
993         cause.clone(),
994         depth,
995         obligations,
996     )
997     .ok()
998     .flatten()
999     .unwrap_or_else(move || {
1000         // if we bottom out in ambiguity, create a type variable
1001         // and a deferred predicate to resolve this when more type
1002         // information is available.
1003
1004         selcx
1005             .infcx()
1006             .infer_projection(param_env, projection_ty, cause, depth + 1, obligations)
1007             .into()
1008     })
1009 }
1010
1011 /// The guts of `normalize`: normalize a specific projection like `<T
1012 /// as Trait>::Item`. The result is always a type (and possibly
1013 /// additional obligations). Returns `None` in the case of ambiguity,
1014 /// which indicates that there are unbound type variables.
1015 ///
1016 /// This function used to return `Option<NormalizedTy<'tcx>>`, which contains a
1017 /// `Ty<'tcx>` and an obligations vector. But that obligation vector was very
1018 /// often immediately appended to another obligations vector. So now this
1019 /// function takes an obligations vector and appends to it directly, which is
1020 /// slightly uglier but avoids the need for an extra short-lived allocation.
1021 #[instrument(level = "debug", skip(selcx, param_env, cause, obligations))]
1022 fn opt_normalize_projection_type<'a, 'b, 'tcx>(
1023     selcx: &'a mut SelectionContext<'b, 'tcx>,
1024     param_env: ty::ParamEnv<'tcx>,
1025     projection_ty: ty::ProjectionTy<'tcx>,
1026     cause: ObligationCause<'tcx>,
1027     depth: usize,
1028     obligations: &mut Vec<PredicateObligation<'tcx>>,
1029 ) -> Result<Option<Term<'tcx>>, InProgress> {
1030     let infcx = selcx.infcx();
1031     // Don't use the projection cache in intercrate mode -
1032     // the `infcx` may be re-used between intercrate in non-intercrate
1033     // mode, which could lead to using incorrect cache results.
1034     let use_cache = !selcx.is_intercrate();
1035
1036     let projection_ty = infcx.resolve_vars_if_possible(projection_ty);
1037     let cache_key = ProjectionCacheKey::new(projection_ty);
1038
1039     // FIXME(#20304) For now, I am caching here, which is good, but it
1040     // means we don't capture the type variables that are created in
1041     // the case of ambiguity. Which means we may create a large stream
1042     // of such variables. OTOH, if we move the caching up a level, we
1043     // would not benefit from caching when proving `T: Trait<U=Foo>`
1044     // bounds. It might be the case that we want two distinct caches,
1045     // or else another kind of cache entry.
1046
1047     let cache_result = if use_cache {
1048         infcx.inner.borrow_mut().projection_cache().try_start(cache_key)
1049     } else {
1050         Ok(())
1051     };
1052     match cache_result {
1053         Ok(()) => debug!("no cache"),
1054         Err(ProjectionCacheEntry::Ambiguous) => {
1055             // If we found ambiguity the last time, that means we will continue
1056             // to do so until some type in the key changes (and we know it
1057             // hasn't, because we just fully resolved it).
1058             debug!("found cache entry: ambiguous");
1059             return Ok(None);
1060         }
1061         Err(ProjectionCacheEntry::InProgress) => {
1062             // Under lazy normalization, this can arise when
1063             // bootstrapping.  That is, imagine an environment with a
1064             // where-clause like `A::B == u32`. Now, if we are asked
1065             // to normalize `A::B`, we will want to check the
1066             // where-clauses in scope. So we will try to unify `A::B`
1067             // with `A::B`, which can trigger a recursive
1068             // normalization.
1069
1070             debug!("found cache entry: in-progress");
1071
1072             // Cache that normalizing this projection resulted in a cycle. This
1073             // should ensure that, unless this happens within a snapshot that's
1074             // rolled back, fulfillment or evaluation will notice the cycle.
1075
1076             if use_cache {
1077                 infcx.inner.borrow_mut().projection_cache().recur(cache_key);
1078             }
1079             return Err(InProgress);
1080         }
1081         Err(ProjectionCacheEntry::Recur) => {
1082             debug!("recur cache");
1083             return Err(InProgress);
1084         }
1085         Err(ProjectionCacheEntry::NormalizedTy { ty, complete: _ }) => {
1086             // This is the hottest path in this function.
1087             //
1088             // If we find the value in the cache, then return it along
1089             // with the obligations that went along with it. Note
1090             // that, when using a fulfillment context, these
1091             // obligations could in principle be ignored: they have
1092             // already been registered when the cache entry was
1093             // created (and hence the new ones will quickly be
1094             // discarded as duplicated). But when doing trait
1095             // evaluation this is not the case, and dropping the trait
1096             // evaluations can causes ICEs (e.g., #43132).
1097             debug!(?ty, "found normalized ty");
1098             obligations.extend(ty.obligations);
1099             return Ok(Some(ty.value));
1100         }
1101         Err(ProjectionCacheEntry::Error) => {
1102             debug!("opt_normalize_projection_type: found error");
1103             let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth);
1104             obligations.extend(result.obligations);
1105             return Ok(Some(result.value.into()));
1106         }
1107     }
1108
1109     let obligation = Obligation::with_depth(cause.clone(), depth, param_env, projection_ty);
1110
1111     match project(selcx, &obligation) {
1112         Ok(Projected::Progress(Progress {
1113             term: projected_term,
1114             obligations: mut projected_obligations,
1115         })) => {
1116             // if projection succeeded, then what we get out of this
1117             // is also non-normalized (consider: it was derived from
1118             // an impl, where-clause etc) and hence we must
1119             // re-normalize it
1120
1121             let projected_term = selcx.infcx().resolve_vars_if_possible(projected_term);
1122
1123             let mut result = if projected_term.has_projections() {
1124                 let mut normalizer = AssocTypeNormalizer::new(
1125                     selcx,
1126                     param_env,
1127                     cause,
1128                     depth + 1,
1129                     &mut projected_obligations,
1130                 );
1131                 let normalized_ty = normalizer.fold(projected_term);
1132
1133                 Normalized { value: normalized_ty, obligations: projected_obligations }
1134             } else {
1135                 Normalized { value: projected_term, obligations: projected_obligations }
1136             };
1137
1138             let mut deduped: SsoHashSet<_> = Default::default();
1139             result.obligations.drain_filter(|projected_obligation| {
1140                 if !deduped.insert(projected_obligation.clone()) {
1141                     return true;
1142                 }
1143                 false
1144             });
1145
1146             if use_cache {
1147                 infcx.inner.borrow_mut().projection_cache().insert_term(cache_key, result.clone());
1148             }
1149             obligations.extend(result.obligations);
1150             Ok(Some(result.value))
1151         }
1152         Ok(Projected::NoProgress(projected_ty)) => {
1153             let result = Normalized { value: projected_ty, obligations: vec![] };
1154             if use_cache {
1155                 infcx.inner.borrow_mut().projection_cache().insert_term(cache_key, result.clone());
1156             }
1157             // No need to extend `obligations`.
1158             Ok(Some(result.value))
1159         }
1160         Err(ProjectionError::TooManyCandidates) => {
1161             debug!("opt_normalize_projection_type: too many candidates");
1162             if use_cache {
1163                 infcx.inner.borrow_mut().projection_cache().ambiguous(cache_key);
1164             }
1165             Ok(None)
1166         }
1167         Err(ProjectionError::TraitSelectionError(_)) => {
1168             debug!("opt_normalize_projection_type: ERROR");
1169             // if we got an error processing the `T as Trait` part,
1170             // just return `ty::err` but add the obligation `T :
1171             // Trait`, which when processed will cause the error to be
1172             // reported later
1173
1174             if use_cache {
1175                 infcx.inner.borrow_mut().projection_cache().error(cache_key);
1176             }
1177             let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth);
1178             obligations.extend(result.obligations);
1179             Ok(Some(result.value.into()))
1180         }
1181     }
1182 }
1183
1184 /// If we are projecting `<T as Trait>::Item`, but `T: Trait` does not
1185 /// hold. In various error cases, we cannot generate a valid
1186 /// normalized projection. Therefore, we create an inference variable
1187 /// return an associated obligation that, when fulfilled, will lead to
1188 /// an error.
1189 ///
1190 /// Note that we used to return `Error` here, but that was quite
1191 /// dubious -- the premise was that an error would *eventually* be
1192 /// reported, when the obligation was processed. But in general once
1193 /// you see an `Error` you are supposed to be able to assume that an
1194 /// error *has been* reported, so that you can take whatever heuristic
1195 /// paths you want to take. To make things worse, it was possible for
1196 /// cycles to arise, where you basically had a setup like `<MyType<$0>
1197 /// as Trait>::Foo == $0`. Here, normalizing `<MyType<$0> as
1198 /// Trait>::Foo> to `[type error]` would lead to an obligation of
1199 /// `<MyType<[type error]> as Trait>::Foo`. We are supposed to report
1200 /// an error for this obligation, but we legitimately should not,
1201 /// because it contains `[type error]`. Yuck! (See issue #29857 for
1202 /// one case where this arose.)
1203 fn normalize_to_error<'a, 'tcx>(
1204     selcx: &mut SelectionContext<'a, 'tcx>,
1205     param_env: ty::ParamEnv<'tcx>,
1206     projection_ty: ty::ProjectionTy<'tcx>,
1207     cause: ObligationCause<'tcx>,
1208     depth: usize,
1209 ) -> NormalizedTy<'tcx> {
1210     let trait_ref = ty::Binder::dummy(projection_ty.trait_ref(selcx.tcx()));
1211     let trait_obligation = Obligation {
1212         cause,
1213         recursion_depth: depth,
1214         param_env,
1215         predicate: trait_ref.without_const().to_predicate(selcx.tcx()),
1216     };
1217     let tcx = selcx.infcx().tcx;
1218     let def_id = projection_ty.item_def_id;
1219     let new_value = selcx.infcx().next_ty_var(TypeVariableOrigin {
1220         kind: TypeVariableOriginKind::NormalizeProjectionType,
1221         span: tcx.def_span(def_id),
1222     });
1223     Normalized { value: new_value, obligations: vec![trait_obligation] }
1224 }
1225
1226 enum Projected<'tcx> {
1227     Progress(Progress<'tcx>),
1228     NoProgress(ty::Term<'tcx>),
1229 }
1230
1231 struct Progress<'tcx> {
1232     term: ty::Term<'tcx>,
1233     obligations: Vec<PredicateObligation<'tcx>>,
1234 }
1235
1236 impl<'tcx> Progress<'tcx> {
1237     fn error(tcx: TyCtxt<'tcx>) -> Self {
1238         Progress { term: tcx.ty_error().into(), obligations: vec![] }
1239     }
1240
1241     fn with_addl_obligations(mut self, mut obligations: Vec<PredicateObligation<'tcx>>) -> Self {
1242         self.obligations.append(&mut obligations);
1243         self
1244     }
1245 }
1246
1247 /// Computes the result of a projection type (if we can).
1248 ///
1249 /// IMPORTANT:
1250 /// - `obligation` must be fully normalized
1251 #[instrument(level = "info", skip(selcx))]
1252 fn project<'cx, 'tcx>(
1253     selcx: &mut SelectionContext<'cx, 'tcx>,
1254     obligation: &ProjectionTyObligation<'tcx>,
1255 ) -> Result<Projected<'tcx>, ProjectionError<'tcx>> {
1256     if !selcx.tcx().recursion_limit().value_within_limit(obligation.recursion_depth) {
1257         // This should really be an immediate error, but some existing code
1258         // relies on being able to recover from this.
1259         return Err(ProjectionError::TraitSelectionError(SelectionError::Overflow(
1260             OverflowError::Canonical,
1261         )));
1262     }
1263
1264     if obligation.predicate.references_error() {
1265         return Ok(Projected::Progress(Progress::error(selcx.tcx())));
1266     }
1267
1268     let mut candidates = ProjectionCandidateSet::None;
1269
1270     assemble_candidate_for_impl_trait_in_trait(selcx, obligation, &mut candidates);
1271
1272     // Make sure that the following procedures are kept in order. ParamEnv
1273     // needs to be first because it has highest priority, and Select checks
1274     // the return value of push_candidate which assumes it's ran at last.
1275     assemble_candidates_from_param_env(selcx, obligation, &mut candidates);
1276
1277     assemble_candidates_from_trait_def(selcx, obligation, &mut candidates);
1278
1279     assemble_candidates_from_object_ty(selcx, obligation, &mut candidates);
1280
1281     if let ProjectionCandidateSet::Single(ProjectionCandidate::Object(_)) = candidates {
1282         // Avoid normalization cycle from selection (see
1283         // `assemble_candidates_from_object_ty`).
1284         // FIXME(lazy_normalization): Lazy normalization should save us from
1285         // having to special case this.
1286     } else {
1287         assemble_candidates_from_impls(selcx, obligation, &mut candidates);
1288     };
1289
1290     match candidates {
1291         ProjectionCandidateSet::Single(candidate) => {
1292             Ok(Projected::Progress(confirm_candidate(selcx, obligation, candidate)))
1293         }
1294         ProjectionCandidateSet::None => Ok(Projected::NoProgress(
1295             // FIXME(associated_const_generics): this may need to change in the future?
1296             // need to investigate whether or not this is fine.
1297             selcx
1298                 .tcx()
1299                 .mk_projection(obligation.predicate.item_def_id, obligation.predicate.substs)
1300                 .into(),
1301         )),
1302         // Error occurred while trying to processing impls.
1303         ProjectionCandidateSet::Error(e) => Err(ProjectionError::TraitSelectionError(e)),
1304         // Inherent ambiguity that prevents us from even enumerating the
1305         // candidates.
1306         ProjectionCandidateSet::Ambiguous => Err(ProjectionError::TooManyCandidates),
1307     }
1308 }
1309
1310 /// If the predicate's item is an `ImplTraitPlaceholder`, we do a select on the
1311 /// corresponding trait ref. If this yields an `impl`, then we're able to project
1312 /// to a concrete type, since we have an `impl`'s method  to provide the RPITIT.
1313 fn assemble_candidate_for_impl_trait_in_trait<'cx, 'tcx>(
1314     selcx: &mut SelectionContext<'cx, 'tcx>,
1315     obligation: &ProjectionTyObligation<'tcx>,
1316     candidate_set: &mut ProjectionCandidateSet<'tcx>,
1317 ) {
1318     let tcx = selcx.tcx();
1319     if tcx.def_kind(obligation.predicate.item_def_id) == DefKind::ImplTraitPlaceholder {
1320         let trait_fn_def_id = tcx.impl_trait_in_trait_parent(obligation.predicate.item_def_id);
1321         let trait_def_id = tcx.parent(trait_fn_def_id);
1322         let trait_substs =
1323             obligation.predicate.substs.truncate_to(tcx, tcx.generics_of(trait_def_id));
1324         // FIXME(named-returns): Binders
1325         let trait_predicate =
1326             ty::Binder::dummy(ty::TraitRef { def_id: trait_def_id, substs: trait_substs })
1327                 .to_poly_trait_predicate();
1328
1329         let _ =
1330             selcx.infcx().commit_if_ok(|_| match selcx.select(&obligation.with(trait_predicate)) {
1331                 Ok(Some(super::ImplSource::UserDefined(data))) => {
1332                     candidate_set.push_candidate(ProjectionCandidate::ImplTraitInTrait(data));
1333                     Ok(())
1334                 }
1335                 Ok(None) => {
1336                     candidate_set.mark_ambiguous();
1337                     return Err(());
1338                 }
1339                 Ok(Some(_)) => {
1340                     // Don't know enough about the impl to provide a useful signature
1341                     return Err(());
1342                 }
1343                 Err(e) => {
1344                     debug!(error = ?e, "selection error");
1345                     candidate_set.mark_error(e);
1346                     return Err(());
1347                 }
1348             });
1349     }
1350 }
1351
1352 /// The first thing we have to do is scan through the parameter
1353 /// environment to see whether there are any projection predicates
1354 /// there that can answer this question.
1355 fn assemble_candidates_from_param_env<'cx, 'tcx>(
1356     selcx: &mut SelectionContext<'cx, 'tcx>,
1357     obligation: &ProjectionTyObligation<'tcx>,
1358     candidate_set: &mut ProjectionCandidateSet<'tcx>,
1359 ) {
1360     assemble_candidates_from_predicates(
1361         selcx,
1362         obligation,
1363         candidate_set,
1364         ProjectionCandidate::ParamEnv,
1365         obligation.param_env.caller_bounds().iter(),
1366         false,
1367     );
1368 }
1369
1370 /// In the case of a nested projection like <<A as Foo>::FooT as Bar>::BarT, we may find
1371 /// that the definition of `Foo` has some clues:
1372 ///
1373 /// ```ignore (illustrative)
1374 /// trait Foo {
1375 ///     type FooT : Bar<BarT=i32>
1376 /// }
1377 /// ```
1378 ///
1379 /// Here, for example, we could conclude that the result is `i32`.
1380 fn assemble_candidates_from_trait_def<'cx, 'tcx>(
1381     selcx: &mut SelectionContext<'cx, 'tcx>,
1382     obligation: &ProjectionTyObligation<'tcx>,
1383     candidate_set: &mut ProjectionCandidateSet<'tcx>,
1384 ) {
1385     debug!("assemble_candidates_from_trait_def(..)");
1386
1387     let tcx = selcx.tcx();
1388     // Check whether the self-type is itself a projection.
1389     // If so, extract what we know from the trait and try to come up with a good answer.
1390     let bounds = match *obligation.predicate.self_ty().kind() {
1391         ty::Projection(ref data) => tcx.bound_item_bounds(data.item_def_id).subst(tcx, data.substs),
1392         ty::Opaque(def_id, substs) => tcx.bound_item_bounds(def_id).subst(tcx, substs),
1393         ty::Infer(ty::TyVar(_)) => {
1394             // If the self-type is an inference variable, then it MAY wind up
1395             // being a projected type, so induce an ambiguity.
1396             candidate_set.mark_ambiguous();
1397             return;
1398         }
1399         _ => return,
1400     };
1401
1402     assemble_candidates_from_predicates(
1403         selcx,
1404         obligation,
1405         candidate_set,
1406         ProjectionCandidate::TraitDef,
1407         bounds.iter(),
1408         true,
1409     );
1410 }
1411
1412 /// In the case of a trait object like
1413 /// `<dyn Iterator<Item = ()> as Iterator>::Item` we can use the existential
1414 /// predicate in the trait object.
1415 ///
1416 /// We don't go through the select candidate for these bounds to avoid cycles:
1417 /// In the above case, `dyn Iterator<Item = ()>: Iterator` would create a
1418 /// nested obligation of `<dyn Iterator<Item = ()> as Iterator>::Item: Sized`,
1419 /// this then has to be normalized without having to prove
1420 /// `dyn Iterator<Item = ()>: Iterator` again.
1421 fn assemble_candidates_from_object_ty<'cx, 'tcx>(
1422     selcx: &mut SelectionContext<'cx, 'tcx>,
1423     obligation: &ProjectionTyObligation<'tcx>,
1424     candidate_set: &mut ProjectionCandidateSet<'tcx>,
1425 ) {
1426     debug!("assemble_candidates_from_object_ty(..)");
1427
1428     let tcx = selcx.tcx();
1429
1430     let self_ty = obligation.predicate.self_ty();
1431     let object_ty = selcx.infcx().shallow_resolve(self_ty);
1432     let data = match object_ty.kind() {
1433         ty::Dynamic(data, ..) => data,
1434         ty::Infer(ty::TyVar(_)) => {
1435             // If the self-type is an inference variable, then it MAY wind up
1436             // being an object type, so induce an ambiguity.
1437             candidate_set.mark_ambiguous();
1438             return;
1439         }
1440         _ => return,
1441     };
1442     let env_predicates = data
1443         .projection_bounds()
1444         .filter(|bound| bound.item_def_id() == obligation.predicate.item_def_id)
1445         .map(|p| p.with_self_ty(tcx, object_ty).to_predicate(tcx));
1446
1447     assemble_candidates_from_predicates(
1448         selcx,
1449         obligation,
1450         candidate_set,
1451         ProjectionCandidate::Object,
1452         env_predicates,
1453         false,
1454     );
1455 }
1456
1457 #[instrument(
1458     level = "debug",
1459     skip(selcx, candidate_set, ctor, env_predicates, potentially_unnormalized_candidates)
1460 )]
1461 fn assemble_candidates_from_predicates<'cx, 'tcx>(
1462     selcx: &mut SelectionContext<'cx, 'tcx>,
1463     obligation: &ProjectionTyObligation<'tcx>,
1464     candidate_set: &mut ProjectionCandidateSet<'tcx>,
1465     ctor: fn(ty::PolyProjectionPredicate<'tcx>) -> ProjectionCandidate<'tcx>,
1466     env_predicates: impl Iterator<Item = ty::Predicate<'tcx>>,
1467     potentially_unnormalized_candidates: bool,
1468 ) {
1469     let infcx = selcx.infcx();
1470     for predicate in env_predicates {
1471         let bound_predicate = predicate.kind();
1472         if let ty::PredicateKind::Projection(data) = predicate.kind().skip_binder() {
1473             let data = bound_predicate.rebind(data);
1474             if data.projection_def_id() != obligation.predicate.item_def_id {
1475                 continue;
1476             }
1477
1478             let is_match = infcx.probe(|_| {
1479                 selcx.match_projection_projections(
1480                     obligation,
1481                     data,
1482                     potentially_unnormalized_candidates,
1483                 )
1484             });
1485
1486             match is_match {
1487                 ProjectionMatchesProjection::Yes => {
1488                     candidate_set.push_candidate(ctor(data));
1489
1490                     if potentially_unnormalized_candidates
1491                         && !obligation.predicate.has_non_region_infer()
1492                     {
1493                         // HACK: Pick the first trait def candidate for a fully
1494                         // inferred predicate. This is to allow duplicates that
1495                         // differ only in normalization.
1496                         return;
1497                     }
1498                 }
1499                 ProjectionMatchesProjection::Ambiguous => {
1500                     candidate_set.mark_ambiguous();
1501                 }
1502                 ProjectionMatchesProjection::No => {}
1503             }
1504         }
1505     }
1506 }
1507
1508 #[instrument(level = "debug", skip(selcx, obligation, candidate_set))]
1509 fn assemble_candidates_from_impls<'cx, 'tcx>(
1510     selcx: &mut SelectionContext<'cx, 'tcx>,
1511     obligation: &ProjectionTyObligation<'tcx>,
1512     candidate_set: &mut ProjectionCandidateSet<'tcx>,
1513 ) {
1514     // Can't assemble candidate from impl for RPITIT
1515     if selcx.tcx().def_kind(obligation.predicate.item_def_id) == DefKind::ImplTraitPlaceholder {
1516         return;
1517     }
1518
1519     // If we are resolving `<T as TraitRef<...>>::Item == Type`,
1520     // start out by selecting the predicate `T as TraitRef<...>`:
1521     let poly_trait_ref = ty::Binder::dummy(obligation.predicate.trait_ref(selcx.tcx()));
1522     let trait_obligation = obligation.with(poly_trait_ref.to_poly_trait_predicate());
1523     let _ = selcx.infcx().commit_if_ok(|_| {
1524         let impl_source = match selcx.select(&trait_obligation) {
1525             Ok(Some(impl_source)) => impl_source,
1526             Ok(None) => {
1527                 candidate_set.mark_ambiguous();
1528                 return Err(());
1529             }
1530             Err(e) => {
1531                 debug!(error = ?e, "selection error");
1532                 candidate_set.mark_error(e);
1533                 return Err(());
1534             }
1535         };
1536
1537         let eligible = match &impl_source {
1538             super::ImplSource::Closure(_)
1539             | super::ImplSource::Generator(_)
1540             | super::ImplSource::FnPointer(_)
1541             | super::ImplSource::TraitAlias(_) => true,
1542             super::ImplSource::UserDefined(impl_data) => {
1543                 // We have to be careful when projecting out of an
1544                 // impl because of specialization. If we are not in
1545                 // codegen (i.e., projection mode is not "any"), and the
1546                 // impl's type is declared as default, then we disable
1547                 // projection (even if the trait ref is fully
1548                 // monomorphic). In the case where trait ref is not
1549                 // fully monomorphic (i.e., includes type parameters),
1550                 // this is because those type parameters may
1551                 // ultimately be bound to types from other crates that
1552                 // may have specialized impls we can't see. In the
1553                 // case where the trait ref IS fully monomorphic, this
1554                 // is a policy decision that we made in the RFC in
1555                 // order to preserve flexibility for the crate that
1556                 // defined the specializable impl to specialize later
1557                 // for existing types.
1558                 //
1559                 // In either case, we handle this by not adding a
1560                 // candidate for an impl if it contains a `default`
1561                 // type.
1562                 //
1563                 // NOTE: This should be kept in sync with the similar code in
1564                 // `rustc_ty_utils::instance::resolve_associated_item()`.
1565                 let node_item =
1566                     assoc_def(selcx, impl_data.impl_def_id, obligation.predicate.item_def_id)
1567                         .map_err(|ErrorGuaranteed { .. }| ())?;
1568
1569                 if node_item.is_final() {
1570                     // Non-specializable items are always projectable.
1571                     true
1572                 } else {
1573                     // Only reveal a specializable default if we're past type-checking
1574                     // and the obligation is monomorphic, otherwise passes such as
1575                     // transmute checking and polymorphic MIR optimizations could
1576                     // get a result which isn't correct for all monomorphizations.
1577                     if obligation.param_env.reveal() == Reveal::All {
1578                         // NOTE(eddyb) inference variables can resolve to parameters, so
1579                         // assume `poly_trait_ref` isn't monomorphic, if it contains any.
1580                         let poly_trait_ref = selcx.infcx().resolve_vars_if_possible(poly_trait_ref);
1581                         !poly_trait_ref.still_further_specializable()
1582                     } else {
1583                         debug!(
1584                             assoc_ty = ?selcx.tcx().def_path_str(node_item.item.def_id),
1585                             ?obligation.predicate,
1586                             "assemble_candidates_from_impls: not eligible due to default",
1587                         );
1588                         false
1589                     }
1590                 }
1591             }
1592             super::ImplSource::DiscriminantKind(..) => {
1593                 // While `DiscriminantKind` is automatically implemented for every type,
1594                 // the concrete discriminant may not be known yet.
1595                 //
1596                 // Any type with multiple potential discriminant types is therefore not eligible.
1597                 let self_ty = selcx.infcx().shallow_resolve(obligation.predicate.self_ty());
1598
1599                 match self_ty.kind() {
1600                     ty::Bool
1601                     | ty::Char
1602                     | ty::Int(_)
1603                     | ty::Uint(_)
1604                     | ty::Float(_)
1605                     | ty::Adt(..)
1606                     | ty::Foreign(_)
1607                     | ty::Str
1608                     | ty::Array(..)
1609                     | ty::Slice(_)
1610                     | ty::RawPtr(..)
1611                     | ty::Ref(..)
1612                     | ty::FnDef(..)
1613                     | ty::FnPtr(..)
1614                     | ty::Dynamic(..)
1615                     | ty::Closure(..)
1616                     | ty::Generator(..)
1617                     | ty::GeneratorWitness(..)
1618                     | ty::Never
1619                     | ty::Tuple(..)
1620                     // Integers and floats always have `u8` as their discriminant.
1621                     | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(..)) => true,
1622
1623                     ty::Projection(..)
1624                     | ty::Opaque(..)
1625                     | ty::Param(..)
1626                     | ty::Bound(..)
1627                     | ty::Placeholder(..)
1628                     | ty::Infer(..)
1629                     | ty::Error(_) => false,
1630                 }
1631             }
1632             super::ImplSource::Pointee(..) => {
1633                 // While `Pointee` is automatically implemented for every type,
1634                 // the concrete metadata type may not be known yet.
1635                 //
1636                 // Any type with multiple potential metadata types is therefore not eligible.
1637                 let self_ty = selcx.infcx().shallow_resolve(obligation.predicate.self_ty());
1638
1639                 let tail = selcx.tcx().struct_tail_with_normalize(
1640                     self_ty,
1641                     |ty| {
1642                         // We throw away any obligations we get from this, since we normalize
1643                         // and confirm these obligations once again during confirmation
1644                         normalize_with_depth(
1645                             selcx,
1646                             obligation.param_env,
1647                             obligation.cause.clone(),
1648                             obligation.recursion_depth + 1,
1649                             ty,
1650                         )
1651                         .value
1652                     },
1653                     || {},
1654                 );
1655
1656                 match tail.kind() {
1657                     ty::Bool
1658                     | ty::Char
1659                     | ty::Int(_)
1660                     | ty::Uint(_)
1661                     | ty::Float(_)
1662                     | ty::Str
1663                     | ty::Array(..)
1664                     | ty::Slice(_)
1665                     | ty::RawPtr(..)
1666                     | ty::Ref(..)
1667                     | ty::FnDef(..)
1668                     | ty::FnPtr(..)
1669                     | ty::Dynamic(..)
1670                     | ty::Closure(..)
1671                     | ty::Generator(..)
1672                     | ty::GeneratorWitness(..)
1673                     | ty::Never
1674                     // Extern types have unit metadata, according to RFC 2850
1675                     | ty::Foreign(_)
1676                     // If returned by `struct_tail_without_normalization` this is a unit struct
1677                     // without any fields, or not a struct, and therefore is Sized.
1678                     | ty::Adt(..)
1679                     // If returned by `struct_tail_without_normalization` this is the empty tuple.
1680                     | ty::Tuple(..)
1681                     // Integers and floats are always Sized, and so have unit type metadata.
1682                     | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(..)) => true,
1683
1684                     // type parameters, opaques, and unnormalized projections have pointer
1685                     // metadata if they're known (e.g. by the param_env) to be sized
1686                     ty::Param(_) | ty::Projection(..) | ty::Opaque(..)
1687                         if selcx.infcx().predicate_must_hold_modulo_regions(
1688                             &obligation.with(
1689                                 ty::Binder::dummy(ty::TraitRef::new(
1690                                     selcx.tcx().require_lang_item(LangItem::Sized, None),
1691                                     selcx.tcx().mk_substs_trait(self_ty, &[]),
1692                                 ))
1693                                 .without_const()
1694                                 .to_predicate(selcx.tcx()),
1695                             ),
1696                         ) =>
1697                     {
1698                         true
1699                     }
1700
1701                     // FIXME(compiler-errors): are Bound and Placeholder types ever known sized?
1702                     ty::Param(_)
1703                     | ty::Projection(..)
1704                     | ty::Opaque(..)
1705                     | ty::Bound(..)
1706                     | ty::Placeholder(..)
1707                     | ty::Infer(..)
1708                     | ty::Error(_) => {
1709                         if tail.has_infer_types() {
1710                             candidate_set.mark_ambiguous();
1711                         }
1712                         false
1713                     }
1714                 }
1715             }
1716             super::ImplSource::Param(..) => {
1717                 // This case tell us nothing about the value of an
1718                 // associated type. Consider:
1719                 //
1720                 // ```
1721                 // trait SomeTrait { type Foo; }
1722                 // fn foo<T:SomeTrait>(...) { }
1723                 // ```
1724                 //
1725                 // If the user writes `<T as SomeTrait>::Foo`, then the `T
1726                 // : SomeTrait` binding does not help us decide what the
1727                 // type `Foo` is (at least, not more specifically than
1728                 // what we already knew).
1729                 //
1730                 // But wait, you say! What about an example like this:
1731                 //
1732                 // ```
1733                 // fn bar<T:SomeTrait<Foo=usize>>(...) { ... }
1734                 // ```
1735                 //
1736                 // Doesn't the `T : SomeTrait<Foo=usize>` predicate help
1737                 // resolve `T::Foo`? And of course it does, but in fact
1738                 // that single predicate is desugared into two predicates
1739                 // in the compiler: a trait predicate (`T : SomeTrait`) and a
1740                 // projection. And the projection where clause is handled
1741                 // in `assemble_candidates_from_param_env`.
1742                 false
1743             }
1744             super::ImplSource::Object(_) => {
1745                 // Handled by the `Object` projection candidate. See
1746                 // `assemble_candidates_from_object_ty` for an explanation of
1747                 // why we special case object types.
1748                 false
1749             }
1750             super::ImplSource::AutoImpl(..)
1751             | super::ImplSource::Builtin(..)
1752             | super::ImplSource::TraitUpcasting(_)
1753             | super::ImplSource::ConstDestruct(_)
1754             | super::ImplSource::Tuple => {
1755                 // These traits have no associated types.
1756                 selcx.tcx().sess.delay_span_bug(
1757                     obligation.cause.span,
1758                     &format!("Cannot project an associated type from `{:?}`", impl_source),
1759                 );
1760                 return Err(());
1761             }
1762         };
1763
1764         if eligible {
1765             if candidate_set.push_candidate(ProjectionCandidate::Select(impl_source)) {
1766                 Ok(())
1767             } else {
1768                 Err(())
1769             }
1770         } else {
1771             Err(())
1772         }
1773     });
1774 }
1775
1776 fn confirm_candidate<'cx, 'tcx>(
1777     selcx: &mut SelectionContext<'cx, 'tcx>,
1778     obligation: &ProjectionTyObligation<'tcx>,
1779     candidate: ProjectionCandidate<'tcx>,
1780 ) -> Progress<'tcx> {
1781     debug!(?obligation, ?candidate, "confirm_candidate");
1782     let mut progress = match candidate {
1783         ProjectionCandidate::ParamEnv(poly_projection)
1784         | ProjectionCandidate::Object(poly_projection) => {
1785             confirm_param_env_candidate(selcx, obligation, poly_projection, false)
1786         }
1787
1788         ProjectionCandidate::TraitDef(poly_projection) => {
1789             confirm_param_env_candidate(selcx, obligation, poly_projection, true)
1790         }
1791
1792         ProjectionCandidate::Select(impl_source) => {
1793             confirm_select_candidate(selcx, obligation, impl_source)
1794         }
1795         ProjectionCandidate::ImplTraitInTrait(data) => {
1796             confirm_impl_trait_in_trait_candidate(selcx, obligation, data)
1797         }
1798     };
1799
1800     // When checking for cycle during evaluation, we compare predicates with
1801     // "syntactic" equality. Since normalization generally introduces a type
1802     // with new region variables, we need to resolve them to existing variables
1803     // when possible for this to work. See `auto-trait-projection-recursion.rs`
1804     // for a case where this matters.
1805     if progress.term.has_infer_regions() {
1806         progress.term =
1807             progress.term.fold_with(&mut OpportunisticRegionResolver::new(selcx.infcx()));
1808     }
1809     progress
1810 }
1811
1812 fn confirm_select_candidate<'cx, 'tcx>(
1813     selcx: &mut SelectionContext<'cx, 'tcx>,
1814     obligation: &ProjectionTyObligation<'tcx>,
1815     impl_source: Selection<'tcx>,
1816 ) -> Progress<'tcx> {
1817     match impl_source {
1818         super::ImplSource::UserDefined(data) => confirm_impl_candidate(selcx, obligation, data),
1819         super::ImplSource::Generator(data) => confirm_generator_candidate(selcx, obligation, data),
1820         super::ImplSource::Closure(data) => confirm_closure_candidate(selcx, obligation, data),
1821         super::ImplSource::FnPointer(data) => confirm_fn_pointer_candidate(selcx, obligation, data),
1822         super::ImplSource::DiscriminantKind(data) => {
1823             confirm_discriminant_kind_candidate(selcx, obligation, data)
1824         }
1825         super::ImplSource::Pointee(data) => confirm_pointee_candidate(selcx, obligation, data),
1826         super::ImplSource::Object(_)
1827         | super::ImplSource::AutoImpl(..)
1828         | super::ImplSource::Param(..)
1829         | super::ImplSource::Builtin(..)
1830         | super::ImplSource::TraitUpcasting(_)
1831         | super::ImplSource::TraitAlias(..)
1832         | super::ImplSource::ConstDestruct(_)
1833         | super::ImplSource::Tuple => {
1834             // we don't create Select candidates with this kind of resolution
1835             span_bug!(
1836                 obligation.cause.span,
1837                 "Cannot project an associated type from `{:?}`",
1838                 impl_source
1839             )
1840         }
1841     }
1842 }
1843
1844 fn confirm_generator_candidate<'cx, 'tcx>(
1845     selcx: &mut SelectionContext<'cx, 'tcx>,
1846     obligation: &ProjectionTyObligation<'tcx>,
1847     impl_source: ImplSourceGeneratorData<'tcx, PredicateObligation<'tcx>>,
1848 ) -> Progress<'tcx> {
1849     let gen_sig = impl_source.substs.as_generator().poly_sig();
1850     let Normalized { value: gen_sig, obligations } = normalize_with_depth(
1851         selcx,
1852         obligation.param_env,
1853         obligation.cause.clone(),
1854         obligation.recursion_depth + 1,
1855         gen_sig,
1856     );
1857
1858     debug!(?obligation, ?gen_sig, ?obligations, "confirm_generator_candidate");
1859
1860     let tcx = selcx.tcx();
1861
1862     let gen_def_id = tcx.require_lang_item(LangItem::Generator, None);
1863
1864     let predicate = super::util::generator_trait_ref_and_outputs(
1865         tcx,
1866         gen_def_id,
1867         obligation.predicate.self_ty(),
1868         gen_sig,
1869     )
1870     .map_bound(|(trait_ref, yield_ty, return_ty)| {
1871         let name = tcx.associated_item(obligation.predicate.item_def_id).name;
1872         let ty = if name == sym::Return {
1873             return_ty
1874         } else if name == sym::Yield {
1875             yield_ty
1876         } else {
1877             bug!()
1878         };
1879
1880         ty::ProjectionPredicate {
1881             projection_ty: ty::ProjectionTy {
1882                 substs: trait_ref.substs,
1883                 item_def_id: obligation.predicate.item_def_id,
1884             },
1885             term: ty.into(),
1886         }
1887     });
1888
1889     confirm_param_env_candidate(selcx, obligation, predicate, false)
1890         .with_addl_obligations(impl_source.nested)
1891         .with_addl_obligations(obligations)
1892 }
1893
1894 fn confirm_discriminant_kind_candidate<'cx, 'tcx>(
1895     selcx: &mut SelectionContext<'cx, 'tcx>,
1896     obligation: &ProjectionTyObligation<'tcx>,
1897     _: ImplSourceDiscriminantKindData,
1898 ) -> Progress<'tcx> {
1899     let tcx = selcx.tcx();
1900
1901     let self_ty = selcx.infcx().shallow_resolve(obligation.predicate.self_ty());
1902     // We get here from `poly_project_and_unify_type` which replaces bound vars
1903     // with placeholders
1904     debug_assert!(!self_ty.has_escaping_bound_vars());
1905     let substs = tcx.mk_substs([self_ty.into()].iter());
1906
1907     let discriminant_def_id = tcx.require_lang_item(LangItem::Discriminant, None);
1908
1909     let predicate = ty::ProjectionPredicate {
1910         projection_ty: ty::ProjectionTy { substs, item_def_id: discriminant_def_id },
1911         term: self_ty.discriminant_ty(tcx).into(),
1912     };
1913
1914     // We get here from `poly_project_and_unify_type` which replaces bound vars
1915     // with placeholders, so dummy is okay here.
1916     confirm_param_env_candidate(selcx, obligation, ty::Binder::dummy(predicate), false)
1917 }
1918
1919 fn confirm_pointee_candidate<'cx, 'tcx>(
1920     selcx: &mut SelectionContext<'cx, 'tcx>,
1921     obligation: &ProjectionTyObligation<'tcx>,
1922     _: ImplSourcePointeeData,
1923 ) -> Progress<'tcx> {
1924     let tcx = selcx.tcx();
1925     let self_ty = selcx.infcx().shallow_resolve(obligation.predicate.self_ty());
1926
1927     let mut obligations = vec![];
1928     let (metadata_ty, check_is_sized) = self_ty.ptr_metadata_ty(tcx, |ty| {
1929         normalize_with_depth_to(
1930             selcx,
1931             obligation.param_env,
1932             obligation.cause.clone(),
1933             obligation.recursion_depth + 1,
1934             ty,
1935             &mut obligations,
1936         )
1937     });
1938     if check_is_sized {
1939         let sized_predicate = ty::Binder::dummy(ty::TraitRef::new(
1940             tcx.require_lang_item(LangItem::Sized, None),
1941             tcx.mk_substs_trait(self_ty, &[]),
1942         ))
1943         .without_const()
1944         .to_predicate(tcx);
1945         obligations.push(Obligation::new(
1946             obligation.cause.clone(),
1947             obligation.param_env,
1948             sized_predicate,
1949         ));
1950     }
1951
1952     let substs = tcx.mk_substs([self_ty.into()].iter());
1953     let metadata_def_id = tcx.require_lang_item(LangItem::Metadata, None);
1954
1955     let predicate = ty::ProjectionPredicate {
1956         projection_ty: ty::ProjectionTy { substs, item_def_id: metadata_def_id },
1957         term: metadata_ty.into(),
1958     };
1959
1960     confirm_param_env_candidate(selcx, obligation, ty::Binder::dummy(predicate), false)
1961         .with_addl_obligations(obligations)
1962 }
1963
1964 fn confirm_fn_pointer_candidate<'cx, 'tcx>(
1965     selcx: &mut SelectionContext<'cx, 'tcx>,
1966     obligation: &ProjectionTyObligation<'tcx>,
1967     fn_pointer_impl_source: ImplSourceFnPointerData<'tcx, PredicateObligation<'tcx>>,
1968 ) -> Progress<'tcx> {
1969     let fn_type = selcx.infcx().shallow_resolve(fn_pointer_impl_source.fn_ty);
1970     let sig = fn_type.fn_sig(selcx.tcx());
1971     let Normalized { value: sig, obligations } = normalize_with_depth(
1972         selcx,
1973         obligation.param_env,
1974         obligation.cause.clone(),
1975         obligation.recursion_depth + 1,
1976         sig,
1977     );
1978
1979     confirm_callable_candidate(selcx, obligation, sig, util::TupleArgumentsFlag::Yes)
1980         .with_addl_obligations(fn_pointer_impl_source.nested)
1981         .with_addl_obligations(obligations)
1982 }
1983
1984 fn confirm_closure_candidate<'cx, 'tcx>(
1985     selcx: &mut SelectionContext<'cx, 'tcx>,
1986     obligation: &ProjectionTyObligation<'tcx>,
1987     impl_source: ImplSourceClosureData<'tcx, PredicateObligation<'tcx>>,
1988 ) -> Progress<'tcx> {
1989     let closure_sig = impl_source.substs.as_closure().sig();
1990     let Normalized { value: closure_sig, obligations } = normalize_with_depth(
1991         selcx,
1992         obligation.param_env,
1993         obligation.cause.clone(),
1994         obligation.recursion_depth + 1,
1995         closure_sig,
1996     );
1997
1998     debug!(?obligation, ?closure_sig, ?obligations, "confirm_closure_candidate");
1999
2000     confirm_callable_candidate(selcx, obligation, closure_sig, util::TupleArgumentsFlag::No)
2001         .with_addl_obligations(impl_source.nested)
2002         .with_addl_obligations(obligations)
2003 }
2004
2005 fn confirm_callable_candidate<'cx, 'tcx>(
2006     selcx: &mut SelectionContext<'cx, 'tcx>,
2007     obligation: &ProjectionTyObligation<'tcx>,
2008     fn_sig: ty::PolyFnSig<'tcx>,
2009     flag: util::TupleArgumentsFlag,
2010 ) -> Progress<'tcx> {
2011     let tcx = selcx.tcx();
2012
2013     debug!(?obligation, ?fn_sig, "confirm_callable_candidate");
2014
2015     let fn_once_def_id = tcx.require_lang_item(LangItem::FnOnce, None);
2016     let fn_once_output_def_id = tcx.require_lang_item(LangItem::FnOnceOutput, None);
2017
2018     let predicate = super::util::closure_trait_ref_and_return_type(
2019         tcx,
2020         fn_once_def_id,
2021         obligation.predicate.self_ty(),
2022         fn_sig,
2023         flag,
2024     )
2025     .map_bound(|(trait_ref, ret_type)| ty::ProjectionPredicate {
2026         projection_ty: ty::ProjectionTy {
2027             substs: trait_ref.substs,
2028             item_def_id: fn_once_output_def_id,
2029         },
2030         term: ret_type.into(),
2031     });
2032
2033     confirm_param_env_candidate(selcx, obligation, predicate, true)
2034 }
2035
2036 fn confirm_param_env_candidate<'cx, 'tcx>(
2037     selcx: &mut SelectionContext<'cx, 'tcx>,
2038     obligation: &ProjectionTyObligation<'tcx>,
2039     poly_cache_entry: ty::PolyProjectionPredicate<'tcx>,
2040     potentially_unnormalized_candidate: bool,
2041 ) -> Progress<'tcx> {
2042     let infcx = selcx.infcx();
2043     let cause = &obligation.cause;
2044     let param_env = obligation.param_env;
2045
2046     let cache_entry = infcx.replace_bound_vars_with_fresh_vars(
2047         cause.span,
2048         LateBoundRegionConversionTime::HigherRankedType,
2049         poly_cache_entry,
2050     );
2051
2052     let cache_projection = cache_entry.projection_ty;
2053     let mut nested_obligations = Vec::new();
2054     let obligation_projection = obligation.predicate;
2055     let obligation_projection = ensure_sufficient_stack(|| {
2056         normalize_with_depth_to(
2057             selcx,
2058             obligation.param_env,
2059             obligation.cause.clone(),
2060             obligation.recursion_depth + 1,
2061             obligation_projection,
2062             &mut nested_obligations,
2063         )
2064     });
2065     let cache_projection = if potentially_unnormalized_candidate {
2066         ensure_sufficient_stack(|| {
2067             normalize_with_depth_to(
2068                 selcx,
2069                 obligation.param_env,
2070                 obligation.cause.clone(),
2071                 obligation.recursion_depth + 1,
2072                 cache_projection,
2073                 &mut nested_obligations,
2074             )
2075         })
2076     } else {
2077         cache_projection
2078     };
2079
2080     debug!(?cache_projection, ?obligation_projection);
2081
2082     match infcx.at(cause, param_env).eq(cache_projection, obligation_projection) {
2083         Ok(InferOk { value: _, obligations }) => {
2084             nested_obligations.extend(obligations);
2085             assoc_ty_own_obligations(selcx, obligation, &mut nested_obligations);
2086             // FIXME(associated_const_equality): Handle consts here as well? Maybe this progress type should just take
2087             // a term instead.
2088             Progress { term: cache_entry.term, obligations: nested_obligations }
2089         }
2090         Err(e) => {
2091             let msg = format!(
2092                 "Failed to unify obligation `{:?}` with poly_projection `{:?}`: {:?}",
2093                 obligation, poly_cache_entry, e,
2094             );
2095             debug!("confirm_param_env_candidate: {}", msg);
2096             let err = infcx.tcx.ty_error_with_message(obligation.cause.span, &msg);
2097             Progress { term: err.into(), obligations: vec![] }
2098         }
2099     }
2100 }
2101
2102 fn confirm_impl_candidate<'cx, 'tcx>(
2103     selcx: &mut SelectionContext<'cx, 'tcx>,
2104     obligation: &ProjectionTyObligation<'tcx>,
2105     impl_impl_source: ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>>,
2106 ) -> Progress<'tcx> {
2107     let tcx = selcx.tcx();
2108
2109     let ImplSourceUserDefinedData { impl_def_id, substs, mut nested } = impl_impl_source;
2110     let assoc_item_id = obligation.predicate.item_def_id;
2111     let trait_def_id = tcx.trait_id_of_impl(impl_def_id).unwrap();
2112
2113     let param_env = obligation.param_env;
2114     let Ok(assoc_ty) = assoc_def(selcx, impl_def_id, assoc_item_id) else {
2115         return Progress { term: tcx.ty_error().into(), obligations: nested };
2116     };
2117
2118     if !assoc_ty.item.defaultness(tcx).has_value() {
2119         // This means that the impl is missing a definition for the
2120         // associated type. This error will be reported by the type
2121         // checker method `check_impl_items_against_trait`, so here we
2122         // just return Error.
2123         debug!(
2124             "confirm_impl_candidate: no associated type {:?} for {:?}",
2125             assoc_ty.item.name, obligation.predicate
2126         );
2127         return Progress { term: tcx.ty_error().into(), obligations: nested };
2128     }
2129     // If we're trying to normalize `<Vec<u32> as X>::A<S>` using
2130     //`impl<T> X for Vec<T> { type A<Y> = Box<Y>; }`, then:
2131     //
2132     // * `obligation.predicate.substs` is `[Vec<u32>, S]`
2133     // * `substs` is `[u32]`
2134     // * `substs` ends up as `[u32, S]`
2135     let substs = obligation.predicate.substs.rebase_onto(tcx, trait_def_id, substs);
2136     let substs =
2137         translate_substs(selcx.infcx(), param_env, impl_def_id, substs, assoc_ty.defining_node);
2138     let ty = tcx.bound_type_of(assoc_ty.item.def_id);
2139     let is_const = matches!(tcx.def_kind(assoc_ty.item.def_id), DefKind::AssocConst);
2140     let term: ty::EarlyBinder<ty::Term<'tcx>> = if is_const {
2141         let identity_substs =
2142             crate::traits::InternalSubsts::identity_for_item(tcx, assoc_ty.item.def_id);
2143         let did = ty::WithOptConstParam::unknown(assoc_ty.item.def_id);
2144         let kind = ty::ConstKind::Unevaluated(ty::UnevaluatedConst::new(did, identity_substs));
2145         ty.map_bound(|ty| tcx.mk_const(ty::ConstS { ty, kind }).into())
2146     } else {
2147         ty.map_bound(|ty| ty.into())
2148     };
2149     if !check_substs_compatible(tcx, &assoc_ty.item, substs) {
2150         let err = tcx.ty_error_with_message(
2151             obligation.cause.span,
2152             "impl item and trait item have different parameters",
2153         );
2154         Progress { term: err.into(), obligations: nested }
2155     } else {
2156         assoc_ty_own_obligations(selcx, obligation, &mut nested);
2157         Progress { term: term.subst(tcx, substs), obligations: nested }
2158     }
2159 }
2160
2161 // Verify that the trait item and its implementation have compatible substs lists
2162 fn check_substs_compatible<'tcx>(
2163     tcx: TyCtxt<'tcx>,
2164     assoc_ty: &ty::AssocItem,
2165     substs: ty::SubstsRef<'tcx>,
2166 ) -> bool {
2167     fn check_substs_compatible_inner<'tcx>(
2168         tcx: TyCtxt<'tcx>,
2169         generics: &'tcx ty::Generics,
2170         args: &'tcx [ty::GenericArg<'tcx>],
2171     ) -> bool {
2172         if generics.count() != args.len() {
2173             return false;
2174         }
2175
2176         let (parent_args, own_args) = args.split_at(generics.parent_count);
2177
2178         if let Some(parent) = generics.parent
2179             && let parent_generics = tcx.generics_of(parent)
2180             && !check_substs_compatible_inner(tcx, parent_generics, parent_args) {
2181             return false;
2182         }
2183
2184         for (param, arg) in std::iter::zip(&generics.params, own_args) {
2185             match (&param.kind, arg.unpack()) {
2186                 (ty::GenericParamDefKind::Type { .. }, ty::GenericArgKind::Type(_))
2187                 | (ty::GenericParamDefKind::Lifetime, ty::GenericArgKind::Lifetime(_))
2188                 | (ty::GenericParamDefKind::Const { .. }, ty::GenericArgKind::Const(_)) => {}
2189                 _ => return false,
2190             }
2191         }
2192
2193         true
2194     }
2195
2196     check_substs_compatible_inner(tcx, tcx.generics_of(assoc_ty.def_id), substs.as_slice())
2197 }
2198
2199 fn confirm_impl_trait_in_trait_candidate<'tcx>(
2200     selcx: &mut SelectionContext<'_, 'tcx>,
2201     obligation: &ProjectionTyObligation<'tcx>,
2202     data: ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>>,
2203 ) -> Progress<'tcx> {
2204     let tcx = selcx.tcx();
2205     let mut obligations = data.nested;
2206
2207     let trait_fn_def_id = tcx.impl_trait_in_trait_parent(obligation.predicate.item_def_id);
2208     let Ok(leaf_def) = assoc_def(selcx, data.impl_def_id, trait_fn_def_id) else {
2209         return Progress { term: tcx.ty_error().into(), obligations };
2210     };
2211     if !leaf_def.item.defaultness(tcx).has_value() {
2212         return Progress { term: tcx.ty_error().into(), obligations };
2213     }
2214
2215     let impl_fn_def_id = leaf_def.item.def_id;
2216     let impl_fn_substs = obligation.predicate.substs.rebase_onto(tcx, trait_fn_def_id, data.substs);
2217
2218     let cause = ObligationCause::new(
2219         obligation.cause.span,
2220         obligation.cause.body_id,
2221         super::ItemObligation(impl_fn_def_id),
2222     );
2223     let predicates = normalize_with_depth_to(
2224         selcx,
2225         obligation.param_env,
2226         cause.clone(),
2227         obligation.recursion_depth + 1,
2228         tcx.predicates_of(impl_fn_def_id).instantiate(tcx, impl_fn_substs),
2229         &mut obligations,
2230     );
2231     obligations.extend(std::iter::zip(predicates.predicates, predicates.spans).map(
2232         |(pred, span)| {
2233             Obligation::with_depth(
2234                 ObligationCause::new(
2235                     obligation.cause.span,
2236                     obligation.cause.body_id,
2237                     if span.is_dummy() {
2238                         super::ItemObligation(impl_fn_def_id)
2239                     } else {
2240                         super::BindingObligation(impl_fn_def_id, span)
2241                     },
2242                 ),
2243                 obligation.recursion_depth + 1,
2244                 obligation.param_env,
2245                 pred,
2246             )
2247         },
2248     ));
2249
2250     let ty = super::normalize_to(
2251         selcx,
2252         obligation.param_env,
2253         cause.clone(),
2254         tcx.bound_trait_impl_trait_tys(impl_fn_def_id)
2255             .map_bound(|tys| {
2256                 tys.map_or_else(|_| tcx.ty_error(), |tys| tys[&obligation.predicate.item_def_id])
2257             })
2258             .subst(tcx, impl_fn_substs),
2259         &mut obligations,
2260     );
2261
2262     Progress { term: ty.into(), obligations }
2263 }
2264
2265 // Get obligations corresponding to the predicates from the where-clause of the
2266 // associated type itself.
2267 fn assoc_ty_own_obligations<'cx, 'tcx>(
2268     selcx: &mut SelectionContext<'cx, 'tcx>,
2269     obligation: &ProjectionTyObligation<'tcx>,
2270     nested: &mut Vec<PredicateObligation<'tcx>>,
2271 ) {
2272     let tcx = selcx.tcx();
2273     for predicate in tcx
2274         .predicates_of(obligation.predicate.item_def_id)
2275         .instantiate_own(tcx, obligation.predicate.substs)
2276         .predicates
2277     {
2278         let normalized = normalize_with_depth_to(
2279             selcx,
2280             obligation.param_env,
2281             obligation.cause.clone(),
2282             obligation.recursion_depth + 1,
2283             predicate,
2284             nested,
2285         );
2286         nested.push(Obligation::with_depth(
2287             obligation.cause.clone(),
2288             obligation.recursion_depth + 1,
2289             obligation.param_env,
2290             normalized,
2291         ));
2292     }
2293 }
2294
2295 /// Locate the definition of an associated type in the specialization hierarchy,
2296 /// starting from the given impl.
2297 ///
2298 /// Based on the "projection mode", this lookup may in fact only examine the
2299 /// topmost impl. See the comments for `Reveal` for more details.
2300 fn assoc_def(
2301     selcx: &SelectionContext<'_, '_>,
2302     impl_def_id: DefId,
2303     assoc_def_id: DefId,
2304 ) -> Result<specialization_graph::LeafDef, ErrorGuaranteed> {
2305     let tcx = selcx.tcx();
2306     let trait_def_id = tcx.impl_trait_ref(impl_def_id).unwrap().def_id;
2307     let trait_def = tcx.trait_def(trait_def_id);
2308
2309     // This function may be called while we are still building the
2310     // specialization graph that is queried below (via TraitDef::ancestors()),
2311     // so, in order to avoid unnecessary infinite recursion, we manually look
2312     // for the associated item at the given impl.
2313     // If there is no such item in that impl, this function will fail with a
2314     // cycle error if the specialization graph is currently being built.
2315     if let Some(&impl_item_id) = tcx.impl_item_implementor_ids(impl_def_id).get(&assoc_def_id) {
2316         let item = tcx.associated_item(impl_item_id);
2317         let impl_node = specialization_graph::Node::Impl(impl_def_id);
2318         return Ok(specialization_graph::LeafDef {
2319             item: *item,
2320             defining_node: impl_node,
2321             finalizing_node: if item.defaultness(tcx).is_default() {
2322                 None
2323             } else {
2324                 Some(impl_node)
2325             },
2326         });
2327     }
2328
2329     let ancestors = trait_def.ancestors(tcx, impl_def_id)?;
2330     if let Some(assoc_item) = ancestors.leaf_def(tcx, assoc_def_id) {
2331         Ok(assoc_item)
2332     } else {
2333         // This is saying that neither the trait nor
2334         // the impl contain a definition for this
2335         // associated type.  Normally this situation
2336         // could only arise through a compiler bug --
2337         // if the user wrote a bad item name, it
2338         // should have failed in astconv.
2339         bug!(
2340             "No associated type `{}` for {}",
2341             tcx.item_name(assoc_def_id),
2342             tcx.def_path_str(impl_def_id)
2343         )
2344     }
2345 }
2346
2347 pub(crate) trait ProjectionCacheKeyExt<'cx, 'tcx>: Sized {
2348     fn from_poly_projection_predicate(
2349         selcx: &mut SelectionContext<'cx, 'tcx>,
2350         predicate: ty::PolyProjectionPredicate<'tcx>,
2351     ) -> Option<Self>;
2352 }
2353
2354 impl<'cx, 'tcx> ProjectionCacheKeyExt<'cx, 'tcx> for ProjectionCacheKey<'tcx> {
2355     fn from_poly_projection_predicate(
2356         selcx: &mut SelectionContext<'cx, 'tcx>,
2357         predicate: ty::PolyProjectionPredicate<'tcx>,
2358     ) -> Option<Self> {
2359         let infcx = selcx.infcx();
2360         // We don't do cross-snapshot caching of obligations with escaping regions,
2361         // so there's no cache key to use
2362         predicate.no_bound_vars().map(|predicate| {
2363             ProjectionCacheKey::new(
2364                 // We don't attempt to match up with a specific type-variable state
2365                 // from a specific call to `opt_normalize_projection_type` - if
2366                 // there's no precise match, the original cache entry is "stranded"
2367                 // anyway.
2368                 infcx.resolve_vars_if_possible(predicate.projection_ty),
2369             )
2370         })
2371     }
2372 }