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