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