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