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