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