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