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