rustc_trait_selection/traits/
project.rs

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