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