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