Skip to main content

rustc_trait_selection/traits/
project.rs

1//! Code for projecting associated types out of trait references.
2
3use std::ops::ControlFlow;
4
5use rustc_attr_ir::lang_items::LangItem;
6use rustc_data_structures::sso::SsoHashSet;
7use rustc_errors::ErrorGuaranteed;
8use rustc_hir::def_id::DefId;
9use rustc_infer::infer::DefineOpaqueTypes;
10use rustc_infer::traits::{ObligationCauseCode, PredicateObligations};
11use rustc_middle::traits::select::OverflowError;
12use rustc_middle::traits::{BuiltinImplSource, ImplSource, ImplSourceUserDefinedData};
13use rustc_middle::ty::fast_reject::DeepRejectCtxt;
14use rustc_middle::ty::{
15    self, CallerBoundsIterator, FieldInfo, Term, Ty, TyCtxt, TypeVisitableExt, TypingMode,
16    Unnormalized, Upcast,
17};
18use rustc_span::{bug, span_bug, sym};
19use tracing::{debug, instrument};
20
21use super::{
22    MismatchedProjectionTypes, Normalized, NormalizedTerm, Obligation, ObligationCause,
23    PredicateObligation, ProjectionCacheEntry, ProjectionCacheKey, Selection, SelectionContext,
24    SelectionError, specialization_graph, translate_args, util,
25};
26use crate::diagnostics::InherentProjectionNormalizationOverflow;
27use crate::error_reporting::traits::report_dyn_incompatibility;
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::PolyProjectionClause<'tcx>>;
34
35pub type ProjectionObligation<'tcx> = Obligation<'tcx, ty::ProjectionClause<'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(#[automatically_derived]impl<'tcx> ::core::fmt::Debug for
    ProjectionError<'tcx> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::TooManyCandidates =>
                ::core::fmt::Formatter::write_str(f, "TooManyCandidates"),
            Self::TraitSelectionError(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "TraitSelectionError", &__self_0),
        }
    }
}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(#[automatically_derived]impl<'tcx> ::core::marker::StructuralPartialEq for
    ProjectionCandidate<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::cmp::PartialEq for
    ProjectionCandidate<'tcx> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::ParamEnv(__self_0), Self::ParamEnv(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::TraitDef(__self_0), Self::TraitDef(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::Object(__self_0), Self::Object(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::Select(__self_0), Self::Select(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => unsafe { ::core::intrinsics::unreachable() }
            }
    }
}PartialEq, #[automatically_derived]impl<'tcx> ::core::cmp::Eq for
    ProjectionCandidate<'tcx> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<ty::PolyProjectionClause<'tcx>>;
        let _: ::core::cmp::AssertParamIsEq<ty::PolyProjectionClause<'tcx>>;
        let _: ::core::cmp::AssertParamIsEq<ty::PolyProjectionClause<'tcx>>;
        let _: ::core::cmp::AssertParamIsEq<Selection<'tcx>>;
    }
}Eq, #[automatically_derived]impl<'tcx> ::core::fmt::Debug for
    ProjectionCandidate<'tcx> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::ParamEnv(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "ParamEnv", &__self_0),
            Self::TraitDef(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "TraitDef", &__self_0),
            Self::Object(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Object", &__self_0),
            Self::Select(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Select", &__self_0),
        }
    }
}Debug)]
52enum ProjectionCandidate<'tcx> {
53    /// From a where-clause in the env or object type
54    ParamEnv(ty::PolyProjectionClause<'tcx>),
55
56    /// From the definition of `Trait` when you have something like
57    /// `<<A as Trait>::B as Trait2>::C`.
58    TraitDef(ty::PolyProjectionClause<'tcx>),
59
60    /// Bounds specified on an object type
61    Object(ty::PolyProjectionClause<'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        // This wacky variable is just used to try and
88        // make code readable and avoid confusing paths.
89        // It is assigned a "value" of `()` only on those
90        // paths in which we wish to convert `*self` to
91        // ambiguous (and return false, because the candidate
92        // was not used). On other paths, it is not assigned,
93        // and hence if those paths *could* reach the code that
94        // comes after the match, this fn would not compile.
95        let convert_to_ambiguous;
96
97        match self {
98            ProjectionCandidateSet::None => {
99                *self = ProjectionCandidateSet::Single(candidate);
100                return true;
101            }
102
103            ProjectionCandidateSet::Single(current) => {
104                // Duplicates can happen inside ParamEnv. In the case, we
105                // perform a lazy deduplication.
106                if current == &candidate {
107                    return false;
108                }
109
110                // Prefer where-clauses. As in select, if there are multiple
111                // candidates, we prefer where-clause candidates over impls. This
112                // may seem a bit surprising, since impls are the source of
113                // "truth" in some sense, but in fact some of the impls that SEEM
114                // applicable are not, because of nested obligations. Where
115                // clauses are the safer choice. See the comment on
116                // `select::SelectionCandidate` and #21974 for more details.
117                match (current, candidate) {
118                    (ProjectionCandidate::ParamEnv(..), ProjectionCandidate::ParamEnv(..)) => {
119                        convert_to_ambiguous = ()
120                    }
121                    (ProjectionCandidate::ParamEnv(..), _) => return false,
122                    (_, ProjectionCandidate::ParamEnv(..)) => ::rustc_span::macros::bug_impl(None,
    format_args!("should never prefer non-param-env candidates over param-env candidates"),
    Location::caller())bug!(
123                        "should never prefer non-param-env candidates over param-env candidates"
124                    ),
125                    (_, _) => convert_to_ambiguous = (),
126                }
127            }
128
129            ProjectionCandidateSet::Ambiguous | ProjectionCandidateSet::Error(..) => {
130                return false;
131            }
132        }
133
134        // We only ever get here when we moved from a single candidate
135        // to ambiguous.
136        let () = convert_to_ambiguous;
137        *self = ProjectionCandidateSet::Ambiguous;
138        false
139    }
140}
141
142/// States returned from `poly_project_and_unify_type`. Takes the place
143/// of the old return type, which was:
144/// ```ignore (not-rust)
145/// Result<
146///     Result<Option<PredicateObligations<'tcx>>, InProgress>,
147///     MismatchedProjectionTypes<'tcx>,
148/// >
149/// ```
150pub(super) enum ProjectAndUnifyResult<'tcx> {
151    /// The projection bound holds subject to the given obligations. If the
152    /// projection cannot be normalized because the required trait bound does
153    /// not hold, this is returned, with `obligations` being a predicate that
154    /// cannot be proven.
155    Holds(PredicateObligations<'tcx>),
156    /// The projection cannot be normalized due to ambiguity. Resolving some
157    /// inference variables in the projection may fix this.
158    FailedNormalization,
159    /// The project cannot be normalized because `poly_project_and_unify_type`
160    /// is called recursively while normalizing the same projection.
161    Recursive,
162    // the projection can be normalized, but is not equal to the expected type.
163    // Returns the type error that arose from the mismatch.
164    MismatchedProjectionTypes(MismatchedProjectionTypes<'tcx>),
165}
166
167/// Evaluates constraints of the form:
168/// ```ignore (not-rust)
169/// for<...> <T as Trait>::U == V
170/// ```
171/// If successful, this may result in additional obligations. Also returns
172/// the projection cache key used to track these additional obligations.
173// FIXME(mgca): While this supports constants, it is only used for types by default right now
174{}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("poly_project_and_unify_term",
                                    "rustc_trait_selection::traits::project",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs"),
                                    ::tracing_core::__macro_support::Option::Some(174u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::project"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("obligation")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("obligation");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligation)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: ProjectAndUnifyResult<'tcx> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let infcx = selcx.infcx;
            let r =
                infcx.commit_if_ok(|_snapshot|
                        {
                            let placeholder_predicate =
                                infcx.enter_forall_and_leak_universe(obligation.predicate);
                            let placeholder_obligation =
                                obligation.with(infcx.tcx, placeholder_predicate);
                            match project_and_unify_term(selcx, &placeholder_obligation)
                                {
                                ProjectAndUnifyResult::MismatchedProjectionTypes(e) =>
                                    Err(e),
                                other => Ok(other),
                            }
                        });
            match r {
                Ok(inner) => inner,
                Err(err) =>
                    ProjectAndUnifyResult::MismatchedProjectionTypes(err),
            }
        }
    }
}#[instrument(level = "debug", skip(selcx))]
175pub(super) fn poly_project_and_unify_term<'cx, 'tcx>(
176    selcx: &mut SelectionContext<'cx, 'tcx>,
177    obligation: &PolyProjectionObligation<'tcx>,
178) -> ProjectAndUnifyResult<'tcx> {
179    let infcx = selcx.infcx;
180    let r = infcx.commit_if_ok(|_snapshot| {
181        let placeholder_predicate = infcx.enter_forall_and_leak_universe(obligation.predicate);
182
183        let placeholder_obligation = obligation.with(infcx.tcx, placeholder_predicate);
184        match project_and_unify_term(selcx, &placeholder_obligation) {
185            ProjectAndUnifyResult::MismatchedProjectionTypes(e) => Err(e),
186            other => Ok(other),
187        }
188    });
189
190    match r {
191        Ok(inner) => inner,
192        Err(err) => ProjectAndUnifyResult::MismatchedProjectionTypes(err),
193    }
194}
195
196/// Evaluates constraints of the form:
197/// ```ignore (not-rust)
198/// <T as Trait>::U == V
199/// ```
200/// If successful, this may result in additional obligations.
201///
202/// See [poly_project_and_unify_term] for an explanation of the return value.
203// FIXME(mgca): While this supports constants, it is only used for types by default right now
204{}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("project_and_unify_term",
                                    "rustc_trait_selection::traits::project",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs"),
                                    ::tracing_core::__macro_support::Option::Some(204u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::project"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("obligation")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("obligation");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligation)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: ProjectAndUnifyResult<'tcx> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let mut obligations = PredicateObligations::new();
            let infcx = selcx.infcx;
            let normalized =
                match opt_normalize_projection_term(selcx,
                        obligation.param_env, obligation.predicate.projection_term,
                        obligation.cause.clone(), obligation.recursion_depth,
                        &mut obligations) {
                    Ok(Some(n)) => n,
                    Ok(None) =>
                        return ProjectAndUnifyResult::FailedNormalization,
                    Err(InProgress) => return ProjectAndUnifyResult::Recursive,
                };
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs:224",
                                    "rustc_trait_selection::traits::project",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs"),
                                    ::tracing_core::__macro_support::Option::Some(224u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::project"),
                                    ::tracing_core::field::FieldSet::new(&["message",
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("normalized")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("normalized");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("obligations")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("obligations");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("project_and_unify_type result")
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&normalized)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligations)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let actual = obligation.predicate.term;
            let InferOk { value: actual, obligations: new } =
                selcx.infcx.replace_opaque_types_with_inference_vars(actual,
                    obligation.cause.body_def_id, obligation.cause.span,
                    obligation.param_env);
            obligations.extend(new);
            match infcx.eq_raw(&obligation.cause, obligation.param_env,
                    DefineOpaqueTypes::Yes, normalized, actual) {
                Ok(InferOk { obligations: inferred_obligations, value: () })
                    => {
                    obligations.extend(inferred_obligations);
                    ProjectAndUnifyResult::Holds(obligations)
                }
                Err(err) => {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs:251",
                                            "rustc_trait_selection::traits::project",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs"),
                                            ::tracing_core::__macro_support::Option::Some(251u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::project"),
                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("equating types encountered error {0:?}",
                                                                        err) as &dyn ::tracing::field::Value))])
                                });
                        } else { ; }
                    };
                    ProjectAndUnifyResult::MismatchedProjectionTypes(MismatchedProjectionTypes {
                            err,
                        })
                }
            }
        }
    }
}#[instrument(level = "debug", skip(selcx))]
205fn project_and_unify_term<'cx, 'tcx>(
206    selcx: &mut SelectionContext<'cx, 'tcx>,
207    obligation: &ProjectionObligation<'tcx>,
208) -> ProjectAndUnifyResult<'tcx> {
209    let mut obligations = PredicateObligations::new();
210
211    let infcx = selcx.infcx;
212    let normalized = match opt_normalize_projection_term(
213        selcx,
214        obligation.param_env,
215        obligation.predicate.projection_term,
216        obligation.cause.clone(),
217        obligation.recursion_depth,
218        &mut obligations,
219    ) {
220        Ok(Some(n)) => n,
221        Ok(None) => return ProjectAndUnifyResult::FailedNormalization,
222        Err(InProgress) => return ProjectAndUnifyResult::Recursive,
223    };
224    debug!(?normalized, ?obligations, "project_and_unify_type result");
225    let actual = obligation.predicate.term;
226    // For an example where this is necessary see tests/ui/impl-trait/nested-return-type2.rs
227    // This allows users to omit re-mentioning all bounds on an associated type and just use an
228    // `impl Trait` for the assoc type to add more bounds.
229    let InferOk { value: actual, obligations: new } =
230        selcx.infcx.replace_opaque_types_with_inference_vars(
231            actual,
232            obligation.cause.body_def_id,
233            obligation.cause.span,
234            obligation.param_env,
235        );
236    obligations.extend(new);
237
238    // Need to define opaque types to support nested opaque types like `impl Fn() -> impl Trait`
239    match infcx.eq_raw(
240        &obligation.cause,
241        obligation.param_env,
242        DefineOpaqueTypes::Yes,
243        normalized,
244        actual,
245    ) {
246        Ok(InferOk { obligations: inferred_obligations, value: () }) => {
247            obligations.extend(inferred_obligations);
248            ProjectAndUnifyResult::Holds(obligations)
249        }
250        Err(err) => {
251            debug!("equating types encountered error {:?}", err);
252            ProjectAndUnifyResult::MismatchedProjectionTypes(MismatchedProjectionTypes { err })
253        }
254    }
255}
256
257/// The guts of `normalize`: normalize a specific projection like `<T
258/// as Trait>::Item`. The result is always a type (and possibly
259/// additional obligations). If ambiguity arises, which implies that
260/// there are unresolved type variables in the projection, we will
261/// instantiate it with a fresh type variable `$X` and generate a new
262/// obligation `<T as Trait>::Item == $X` for later.
263// FIXME(mgca): While this supports constants, it is only used for types by default right now
264pub fn normalize_projection_term<'a, 'b, 'tcx>(
265    selcx: &'a mut SelectionContext<'b, 'tcx>,
266    param_env: ty::ParamEnv<'tcx>,
267    alias_term: ty::AliasTerm<'tcx>,
268    cause: ObligationCause<'tcx>,
269    depth: usize,
270    obligations: &mut PredicateObligations<'tcx>,
271) -> Term<'tcx> {
272    opt_normalize_projection_term(selcx, param_env, alias_term, cause.clone(), depth, obligations)
273        .ok()
274        .flatten()
275        .unwrap_or_else(move || {
276            // if we bottom out in ambiguity, create a type variable
277            // and a deferred predicate to resolve this when more type
278            // information is available.
279
280            selcx.infcx.projection_term_to_infer(
281                param_env,
282                alias_term,
283                cause,
284                depth + 1,
285                obligations,
286            )
287        })
288}
289
290/// The guts of `normalize`: normalize a specific projection like `<T
291/// as Trait>::Item`. The result is always a type (and possibly
292/// additional obligations). Returns `None` in the case of ambiguity,
293/// which indicates that there are unbound type variables.
294///
295/// This function used to return `Option<NormalizedTy<'tcx>>`, which contains a
296/// `Ty<'tcx>` and an obligations vector. But that obligation vector was very
297/// often immediately appended to another obligations vector. So now this
298/// function takes an obligations vector and appends to it directly, which is
299/// slightly uglier but avoids the need for an extra short-lived allocation.
300// FIXME(mgca): While this supports constants, it is only used for types by default right now
301{}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("opt_normalize_projection_term",
                                    "rustc_trait_selection::traits::project",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs"),
                                    ::tracing_core::__macro_support::Option::Some(301u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::project"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("projection_term")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("projection_term");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("depth")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("depth");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&projection_term)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&depth as
                                                            &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    Result<Option<Term<'tcx>>, InProgress> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let infcx = selcx.infcx;
            if true {
                if !!selcx.infcx.next_trait_solver() {
                    ::core::panicking::panic("assertion failed: !selcx.infcx.next_trait_solver()")
                };
            };
            let projection_term =
                infcx.deeply_resolve_ignoring_regions(projection_term);
            let cache_key =
                ProjectionCacheKey::new(projection_term, param_env);
            let cache_entry =
                infcx.inner.borrow_mut().projection_cache().try_start(cache_key);
            match cache_entry {
                Ok(()) => {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs:324",
                                        "rustc_trait_selection::traits::project",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs"),
                                        ::tracing_core::__macro_support::Option::Some(324u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::project"),
                                        ::tracing_core::field::FieldSet::new(&["message"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("no cache")
                                                            as &dyn ::tracing::field::Value))])
                            });
                    } else { ; }
                }
                Err(ProjectionCacheEntry::Ambiguous) => {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs:329",
                                            "rustc_trait_selection::traits::project",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs"),
                                            ::tracing_core::__macro_support::Option::Some(329u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::project"),
                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("found cache entry: ambiguous")
                                                                as &dyn ::tracing::field::Value))])
                                });
                        } else { ; }
                    };
                    return Ok(None);
                }
                Err(ProjectionCacheEntry::InProgress) => {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs:341",
                                            "rustc_trait_selection::traits::project",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs"),
                                            ::tracing_core::__macro_support::Option::Some(341u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::project"),
                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("found cache entry: in-progress")
                                                                as &dyn ::tracing::field::Value))])
                                });
                        } else { ; }
                    };
                    infcx.inner.borrow_mut().projection_cache().recur(cache_key);
                    return Err(InProgress);
                }
                Err(ProjectionCacheEntry::Recur) => {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs:350",
                                            "rustc_trait_selection::traits::project",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs"),
                                            ::tracing_core::__macro_support::Option::Some(350u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::project"),
                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("recur cache")
                                                                as &dyn ::tracing::field::Value))])
                                });
                        } else { ; }
                    };
                    return Err(InProgress);
                }
                Err(ProjectionCacheEntry::NormalizedTerm { ty, complete: _ })
                    => {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs:365",
                                            "rustc_trait_selection::traits::project",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs"),
                                            ::tracing_core::__macro_support::Option::Some(365u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::project"),
                                            ::tracing_core::field::FieldSet::new(&["message",
                                                            {
                                                                const NAME:
                                                                    ::tracing::__macro_support::FieldName<{
                                                                        ::tracing::__macro_support::FieldName::len("ty")
                                                                    }> =
                                                                    ::tracing::__macro_support::FieldName::new("ty");
                                                                NAME.as_str()
                                                            }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("found normalized ty")
                                                                as &dyn ::tracing::field::Value)),
                                                    (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
                                                                as &dyn ::tracing::field::Value))])
                                });
                        } else { ; }
                    };
                    obligations.extend(ty.obligations);
                    return Ok(Some(ty.value));
                }
                Err(ProjectionCacheEntry::Error) => {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs:370",
                                            "rustc_trait_selection::traits::project",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs"),
                                            ::tracing_core::__macro_support::Option::Some(370u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::project"),
                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("opt_normalize_projection_type: found error")
                                                                as &dyn ::tracing::field::Value))])
                                });
                        } else { ; }
                    };
                    let result =
                        normalize_to_error(selcx, param_env, projection_term, cause,
                            depth);
                    obligations.extend(result.obligations);
                    return Ok(Some(result.value));
                }
            }
            let obligation =
                Obligation::with_depth(selcx.tcx(), cause.clone(), depth,
                    param_env, projection_term);
            match project(selcx, &obligation) {
                Ok(Projected::Progress(Progress {
                    term: projected_term, obligations: mut projected_obligations
                    })) => {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs:385",
                                            "rustc_trait_selection::traits::project",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs"),
                                            ::tracing_core::__macro_support::Option::Some(385u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::project"),
                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("opt_normalize_projection_type: progress")
                                                                as &dyn ::tracing::field::Value))])
                                });
                        } else { ; }
                    };
                    let projected_term =
                        selcx.infcx.deeply_resolve_ignoring_regions(projected_term);
                    let mut result =
                        if projected_term.has_aliases() {
                            let normalized_ty =
                                normalize_with_depth_to(selcx, param_env, cause, depth + 1,
                                    projected_term, &mut projected_obligations);
                            Normalized {
                                value: normalized_ty,
                                obligations: projected_obligations,
                            }
                        } else {
                            Normalized {
                                value: projected_term.skip_normalization(),
                                obligations: projected_obligations,
                            }
                        };
                    let mut deduped =
                        SsoHashSet::with_capacity(result.obligations.len());
                    result.obligations.retain(|obligation|
                            deduped.insert(obligation.clone()));
                    infcx.inner.borrow_mut().projection_cache().insert_term(cache_key,
                        result.clone());
                    obligations.extend(result.obligations);
                    Ok(Some(result.value))
                }
                Ok(Projected::NoProgress(projected_ty)) => {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs:419",
                                            "rustc_trait_selection::traits::project",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs"),
                                            ::tracing_core::__macro_support::Option::Some(419u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::project"),
                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("opt_normalize_projection_type: no progress")
                                                                as &dyn ::tracing::field::Value))])
                                });
                        } else { ; }
                    };
                    let result =
                        Normalized {
                            value: projected_ty,
                            obligations: PredicateObligations::new(),
                        };
                    infcx.inner.borrow_mut().projection_cache().insert_term(cache_key,
                        result.clone());
                    Ok(Some(result.value))
                }
                Err(ProjectionError::TooManyCandidates) => {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs:427",
                                            "rustc_trait_selection::traits::project",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs"),
                                            ::tracing_core::__macro_support::Option::Some(427u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::project"),
                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("opt_normalize_projection_type: too many candidates")
                                                                as &dyn ::tracing::field::Value))])
                                });
                        } else { ; }
                    };
                    infcx.inner.borrow_mut().projection_cache().ambiguous(cache_key);
                    Ok(None)
                }
                Err(ProjectionError::TraitSelectionError(_)) => {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs:432",
                                            "rustc_trait_selection::traits::project",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs"),
                                            ::tracing_core::__macro_support::Option::Some(432u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::project"),
                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("opt_normalize_projection_type: ERROR")
                                                                as &dyn ::tracing::field::Value))])
                                });
                        } else { ; }
                    };
                    infcx.inner.borrow_mut().projection_cache().error(cache_key);
                    let result =
                        normalize_to_error(selcx, param_env, projection_term, cause,
                            depth);
                    obligations.extend(result.obligations);
                    Ok(Some(result.value))
                }
            }
        }
    }
}#[instrument(level = "debug", skip(selcx, param_env, cause, obligations))]
302pub(super) fn opt_normalize_projection_term<'a, 'b, 'tcx>(
303    selcx: &'a mut SelectionContext<'b, 'tcx>,
304    param_env: ty::ParamEnv<'tcx>,
305    projection_term: ty::AliasTerm<'tcx>,
306    cause: ObligationCause<'tcx>,
307    depth: usize,
308    obligations: &mut PredicateObligations<'tcx>,
309) -> Result<Option<Term<'tcx>>, InProgress> {
310    let infcx = selcx.infcx;
311    debug_assert!(!selcx.infcx.next_trait_solver());
312    let projection_term = infcx.deeply_resolve_ignoring_regions(projection_term);
313    let cache_key = ProjectionCacheKey::new(projection_term, param_env);
314
315    // FIXME(#20304) For now, I am caching here, which is good, but it
316    // means we don't capture the type variables that are created in
317    // the case of ambiguity. Which means we may create a large stream
318    // of such variables. OTOH, if we move the caching up a level, we
319    // would not benefit from caching when proving `T: Trait<U=Foo>`
320    // bounds. It might be the case that we want two distinct caches,
321    // or else another kind of cache entry.
322    let cache_entry = infcx.inner.borrow_mut().projection_cache().try_start(cache_key);
323    match cache_entry {
324        Ok(()) => debug!("no cache"),
325        Err(ProjectionCacheEntry::Ambiguous) => {
326            // If we found ambiguity the last time, that means we will continue
327            // to do so until some type in the key changes (and we know it
328            // hasn't, because we just fully resolved it).
329            debug!("found cache entry: ambiguous");
330            return Ok(None);
331        }
332        Err(ProjectionCacheEntry::InProgress) => {
333            // Under lazy normalization, this can arise when
334            // bootstrapping. That is, imagine an environment with a
335            // where-clause like `A::B == u32`. Now, if we are asked
336            // to normalize `A::B`, we will want to check the
337            // where-clauses in scope. So we will try to unify `A::B`
338            // with `A::B`, which can trigger a recursive
339            // normalization.
340
341            debug!("found cache entry: in-progress");
342
343            // Cache that normalizing this projection resulted in a cycle. This
344            // should ensure that, unless this happens within a snapshot that's
345            // rolled back, fulfillment or evaluation will notice the cycle.
346            infcx.inner.borrow_mut().projection_cache().recur(cache_key);
347            return Err(InProgress);
348        }
349        Err(ProjectionCacheEntry::Recur) => {
350            debug!("recur cache");
351            return Err(InProgress);
352        }
353        Err(ProjectionCacheEntry::NormalizedTerm { ty, complete: _ }) => {
354            // This is the hottest path in this function.
355            //
356            // If we find the value in the cache, then return it along
357            // with the obligations that went along with it. Note
358            // that, when using a fulfillment context, these
359            // obligations could in principle be ignored: they have
360            // already been registered when the cache entry was
361            // created (and hence the new ones will quickly be
362            // discarded as duplicated). But when doing trait
363            // evaluation this is not the case, and dropping the trait
364            // evaluations can causes ICEs (e.g., #43132).
365            debug!(?ty, "found normalized ty");
366            obligations.extend(ty.obligations);
367            return Ok(Some(ty.value));
368        }
369        Err(ProjectionCacheEntry::Error) => {
370            debug!("opt_normalize_projection_type: found error");
371            let result = normalize_to_error(selcx, param_env, projection_term, cause, depth);
372            obligations.extend(result.obligations);
373            return Ok(Some(result.value));
374        }
375    }
376
377    let obligation =
378        Obligation::with_depth(selcx.tcx(), cause.clone(), depth, param_env, projection_term);
379
380    match project(selcx, &obligation) {
381        Ok(Projected::Progress(Progress {
382            term: projected_term,
383            obligations: mut projected_obligations,
384        })) => {
385            debug!("opt_normalize_projection_type: progress");
386            // if projection succeeded, then what we get out of this
387            // is also non-normalized (consider: it was derived from
388            // an impl, where-clause etc) and hence we must
389            // re-normalize it
390
391            let projected_term = selcx.infcx.deeply_resolve_ignoring_regions(projected_term);
392
393            let mut result = if projected_term.has_aliases() {
394                let normalized_ty = normalize_with_depth_to(
395                    selcx,
396                    param_env,
397                    cause,
398                    depth + 1,
399                    projected_term,
400                    &mut projected_obligations,
401                );
402
403                Normalized { value: normalized_ty, obligations: projected_obligations }
404            } else {
405                Normalized {
406                    value: projected_term.skip_normalization(),
407                    obligations: projected_obligations,
408                }
409            };
410
411            let mut deduped = SsoHashSet::with_capacity(result.obligations.len());
412            result.obligations.retain(|obligation| deduped.insert(obligation.clone()));
413
414            infcx.inner.borrow_mut().projection_cache().insert_term(cache_key, result.clone());
415            obligations.extend(result.obligations);
416            Ok(Some(result.value))
417        }
418        Ok(Projected::NoProgress(projected_ty)) => {
419            debug!("opt_normalize_projection_type: no progress");
420            let result =
421                Normalized { value: projected_ty, obligations: PredicateObligations::new() };
422            infcx.inner.borrow_mut().projection_cache().insert_term(cache_key, result.clone());
423            // No need to extend `obligations`.
424            Ok(Some(result.value))
425        }
426        Err(ProjectionError::TooManyCandidates) => {
427            debug!("opt_normalize_projection_type: too many candidates");
428            infcx.inner.borrow_mut().projection_cache().ambiguous(cache_key);
429            Ok(None)
430        }
431        Err(ProjectionError::TraitSelectionError(_)) => {
432            debug!("opt_normalize_projection_type: ERROR");
433            // if we got an error processing the `T as Trait` part,
434            // just return `ty::err` but add the obligation `T :
435            // Trait`, which when processed will cause the error to be
436            // reported later
437            infcx.inner.borrow_mut().projection_cache().error(cache_key);
438            let result = normalize_to_error(selcx, param_env, projection_term, cause, depth);
439            obligations.extend(result.obligations);
440            Ok(Some(result.value))
441        }
442    }
443}
444
445/// If we are projecting `<T as Trait>::Item`, but `T: Trait` does not
446/// hold. In various error cases, we cannot generate a valid
447/// normalized projection. Therefore, we create an inference variable
448/// return an associated obligation that, when fulfilled, will lead to
449/// an error.
450///
451/// Note that we used to return `Error` here, but that was quite
452/// dubious -- the premise was that an error would *eventually* be
453/// reported, when the obligation was processed. But in general once
454/// you see an `Error` you are supposed to be able to assume that an
455/// error *has been* reported, so that you can take whatever heuristic
456/// paths you want to take. To make things worse, it was possible for
457/// cycles to arise, where you basically had a setup like `<MyType<$0>
458/// as Trait>::Foo == $0`. Here, normalizing `<MyType<$0> as
459/// Trait>::Foo>` to `[type error]` would lead to an obligation of
460/// `<MyType<[type error]> as Trait>::Foo`. We are supposed to report
461/// an error for this obligation, but we legitimately should not,
462/// because it contains `[type error]`. Yuck! (See issue #29857 for
463/// one case where this arose.)
464// FIXME(mgca): While this supports constants, it is only used for types by default right now
465fn normalize_to_error<'a, 'tcx>(
466    selcx: &SelectionContext<'a, 'tcx>,
467    param_env: ty::ParamEnv<'tcx>,
468    projection_term: ty::AliasTerm<'tcx>,
469    cause: ObligationCause<'tcx>,
470    depth: usize,
471) -> NormalizedTerm<'tcx> {
472    let trait_ref = ty::Binder::dummy(projection_term.trait_ref(selcx.tcx()));
473    let new_value = selcx.infcx.next_term_var_of_alias_kind(projection_term, cause.span);
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/// When normalizing a const alias, register a `ConstArgHasType` obligation
485/// to ensure the const value's type matches the declared type.
486fn push_const_arg_has_type_obligation<'tcx>(
487    tcx: TyCtxt<'tcx>,
488    obligations: &mut PredicateObligations<'tcx>,
489    cause: &ObligationCause<'tcx>,
490    depth: usize,
491    param_env: ty::ParamEnv<'tcx>,
492    term: Term<'tcx>,
493    def_id: DefId,
494    args: ty::GenericArgs<'tcx>,
495) {
496    if let Some(ct) = term.as_const() {
497        let expected_ty = tcx.type_of(def_id).instantiate(tcx, args).skip_norm_wip();
498        obligations.push(Obligation::with_depth(
499            tcx,
500            cause.clone(),
501            depth,
502            param_env,
503            ty::ClauseKind::ConstArgHasType(ct, expected_ty),
504        ));
505    }
506}
507
508/// The old solver does not support references to non-type-consts.
509/// Emit a delayed bug if there is a type system reference to a non type const, as this should have
510/// already errored elsewhere.
511pub fn const_of_item_or_delayed_bug<'tcx>(
512    tcx: TyCtxt<'tcx>,
513    def_id: DefId,
514) -> ty::EarlyBinder<'tcx, ty::Const<'tcx>> {
515    tcx.const_of_item(def_id).unwrap_or_else(|| {
516        let e = tcx.dcx().span_delayed_bug(
517            tcx.def_span(def_id),
518            "encountered regular consts in the old solver's const normalization",
519        );
520        ty::EarlyBinder::bind(tcx, ty::Const::new_error(tcx, e))
521    })
522}
523
524/// Confirm and normalize the given inherent projection.
525// FIXME(mgca): While this supports constants, it is only used for types by default right now
526{}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("normalize_inherent_projection",
                                    "rustc_trait_selection::traits::project",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs"),
                                    ::tracing_core::__macro_support::Option::Some(526u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::project"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("alias_term")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("alias_term");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("depth")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("depth");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&alias_term)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&depth as
                                                            &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: ty::Term<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if true {
                if !!selcx.infcx.next_trait_solver() {
                    ::core::panicking::panic("assertion failed: !selcx.infcx.next_trait_solver()")
                };
            };
            let tcx = selcx.tcx();
            if !tcx.recursion_limit().value_within_limit(depth) {
                tcx.dcx().emit_fatal(InherentProjectionNormalizationOverflow {
                        span: cause.span,
                        ty: alias_term.to_string(),
                    });
            }
            let args =
                compute_inherent_assoc_term_args(selcx, param_env, alias_term,
                    cause.clone(), depth, obligations);
            let def_id = alias_term.expect_inherent_def_id();
            let clauses = tcx.clauses_of(def_id).instantiate(tcx, args);
            for (clause, span) in clauses {
                let clause =
                    normalize_with_depth_to(selcx, param_env, cause.clone(),
                        depth + 1, clause, obligations);
                let nested_cause =
                    ObligationCause::new(cause.span, cause.body_def_id,
                        ObligationCauseCode::WhereClause(def_id, span));
                obligations.push(Obligation::with_depth(tcx, nested_cause,
                        depth + 1, param_env, clause));
            }
            let term =
                if alias_term.kind.is_type() {
                    tcx.type_of(def_id).instantiate(tcx, args).map(Into::into)
                } else {
                    const_of_item_or_delayed_bug(tcx,
                                def_id).instantiate(tcx, args).map(Into::into)
                };
            let term = selcx.infcx.deeply_resolve_ignoring_regions(term);
            let term =
                normalize_with_depth_to(selcx, param_env, cause.clone(),
                    depth + 1, term, obligations);
            push_const_arg_has_type_obligation(tcx, obligations, &cause,
                depth + 1, param_env, term, def_id, args);
            term
        }
    }
}#[instrument(level = "debug", skip(selcx, param_env, cause, obligations))]
527pub fn normalize_inherent_projection<'a, 'b, 'tcx>(
528    selcx: &'a mut SelectionContext<'b, 'tcx>,
529    param_env: ty::ParamEnv<'tcx>,
530    alias_term: ty::AliasTerm<'tcx>,
531    cause: ObligationCause<'tcx>,
532    depth: usize,
533    obligations: &mut PredicateObligations<'tcx>,
534) -> ty::Term<'tcx> {
535    debug_assert!(!selcx.infcx.next_trait_solver());
536    let tcx = selcx.tcx();
537
538    if !tcx.recursion_limit().value_within_limit(depth) {
539        // Halt compilation because it is important that overflows never be masked.
540        tcx.dcx().emit_fatal(InherentProjectionNormalizationOverflow {
541            span: cause.span,
542            ty: alias_term.to_string(),
543        });
544    }
545
546    let args = compute_inherent_assoc_term_args(
547        selcx,
548        param_env,
549        alias_term,
550        cause.clone(),
551        depth,
552        obligations,
553    );
554
555    // Register the obligations arising from the impl and from the associated type itself.
556    let def_id = alias_term.expect_inherent_def_id();
557    let clauses = tcx.clauses_of(def_id).instantiate(tcx, args);
558    for (clause, span) in clauses {
559        let clause = normalize_with_depth_to(
560            selcx,
561            param_env,
562            cause.clone(),
563            depth + 1,
564            clause,
565            obligations,
566        );
567
568        let nested_cause = ObligationCause::new(
569            cause.span,
570            cause.body_def_id,
571            // FIXME(inherent_associated_types): Since we can't pass along the self type to the
572            // cause code, inherent projections will be printed with identity instantiation in
573            // diagnostics which is not ideal.
574            // Consider creating separate cause codes for this specific situation.
575            ObligationCauseCode::WhereClause(def_id, span),
576        );
577
578        obligations.push(Obligation::with_depth(tcx, nested_cause, depth + 1, param_env, clause));
579    }
580
581    let term = if alias_term.kind.is_type() {
582        tcx.type_of(def_id).instantiate(tcx, args).map(Into::into)
583    } else {
584        const_of_item_or_delayed_bug(tcx, def_id).instantiate(tcx, args).map(Into::into)
585    };
586
587    let term = selcx.infcx.deeply_resolve_ignoring_regions(term);
588    let term =
589        normalize_with_depth_to(selcx, param_env, cause.clone(), depth + 1, term, obligations);
590
591    push_const_arg_has_type_obligation(
592        tcx,
593        obligations,
594        &cause,
595        depth + 1,
596        param_env,
597        term,
598        def_id,
599        args,
600    );
601
602    term
603}
604
605// FIXME(mgca): While this supports constants, it is only used for types by default right now
606pub fn compute_inherent_assoc_term_args<'a, 'b, 'tcx>(
607    selcx: &'a mut SelectionContext<'b, 'tcx>,
608    param_env: ty::ParamEnv<'tcx>,
609    alias_term: ty::AliasTerm<'tcx>,
610    cause: ObligationCause<'tcx>,
611    depth: usize,
612    obligations: &mut PredicateObligations<'tcx>,
613) -> ty::GenericArgs<'tcx> {
614    let tcx = selcx.tcx();
615
616    let alias_def_id = match alias_term.kind {
617        ty::AliasTermKind::InherentTy { def_id } => def_id,
618        ty::AliasTermKind::InherentConstSelf { def_id } => def_id,
619        ty::AliasTermKind::InherentConstImpl { .. } => return alias_term.args,
620        kind => {
    ::core::panicking::panic_fmt(format_args!("expected inherent alias, found {0:?}",
            kind));
}panic!("expected inherent alias, found {kind:?}"),
621    };
622
623    let impl_def_id = tcx.parent(alias_def_id);
624    let impl_args = selcx.infcx.fresh_args_for_item(cause.span, impl_def_id);
625
626    let impl_ty = tcx.type_of(impl_def_id).instantiate(tcx, impl_args);
627    let impl_ty = if !selcx.infcx.next_trait_solver() {
628        normalize_with_depth_to(selcx, param_env, cause.clone(), depth + 1, impl_ty, obligations)
629    } else {
630        impl_ty.skip_norm_wip()
631    };
632
633    // Infer the generic parameters of the impl by unifying the
634    // impl type with the self type of the projection.
635    let self_ty = ty::Unnormalized::new_wip(alias_term.self_ty());
636    let self_ty = if !selcx.infcx.next_trait_solver() {
637        normalize_with_depth_to(selcx, param_env, cause.clone(), depth + 1, self_ty, obligations)
638    } else {
639        self_ty.skip_normalization()
640    };
641
642    match selcx.infcx.eq_raw(&cause, param_env, DefineOpaqueTypes::Yes, impl_ty, self_ty) {
643        Ok(mut ok) => obligations.append(&mut ok.obligations),
644        Err(_) => {
645            tcx.dcx().span_bug(
646                cause.span,
647                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?} was equal to {1:?} during selection but now it is not",
                self_ty, impl_ty))
    })format!("{self_ty:?} was equal to {impl_ty:?} during selection but now it is not"),
648            );
649        }
650    }
651
652    alias_term.rebase_inherent_args_onto_impl(impl_args, tcx)
653}
654
655enum Projected<'tcx> {
656    Progress(Progress<'tcx>),
657    NoProgress(ty::Term<'tcx>),
658}
659
660struct Progress<'tcx> {
661    term: ty::Unnormalized<'tcx, ty::Term<'tcx>>,
662    obligations: PredicateObligations<'tcx>,
663}
664
665impl<'tcx> Progress<'tcx> {
666    fn error_for_term(
667        tcx: TyCtxt<'tcx>,
668        alias_term: ty::AliasTerm<'tcx>,
669        guar: ErrorGuaranteed,
670    ) -> Self {
671        let err_term = if alias_term.kind.is_type() {
672            Ty::new_error(tcx, guar).into()
673        } else {
674            ty::Const::new_error(tcx, guar).into()
675        };
676        Progress {
677            term: ty::Unnormalized::dummy(err_term),
678            obligations: PredicateObligations::new(),
679        }
680    }
681
682    fn with_addl_obligations(mut self, mut obligations: PredicateObligations<'tcx>) -> Self {
683        self.obligations.append(&mut obligations);
684        self
685    }
686}
687
688/// Computes the result of a projection type (if we can).
689///
690/// IMPORTANT:
691/// - `obligation` must be fully normalized
692// FIXME(mgca): While this supports constants, it is only used for types by default right now
693{}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
                ::tracing::Level::INFO <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("project",
                                    "rustc_trait_selection::traits::project",
                                    ::tracing::Level::INFO,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs"),
                                    ::tracing_core::__macro_support::Option::Some(693u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::project"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("obligation")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("obligation");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::INFO <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::INFO <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligation)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    Result<Projected<'tcx>, ProjectionError<'tcx>> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if !selcx.tcx().recursion_limit().value_within_limit(obligation.recursion_depth)
                {
                return Err(ProjectionError::TraitSelectionError(SelectionError::Overflow(OverflowError::Canonical)));
            }
            if let Err(guar) =
                    obligation.predicate.non_region_error_reported() {
                return Ok(Projected::Progress(Progress::error_for_term(selcx.tcx(),
                                obligation.predicate, guar)));
            }
            let self_ty =
                selcx.infcx.shallow_resolve(obligation.predicate.self_ty());
            if let ty::Dynamic(data, ..) = self_ty.kind() {
                if let Some(def_id) = data.principal_def_id() {
                    let tcx = selcx.tcx();
                    if !tcx.is_dyn_compatible(def_id) {
                        let span = obligation.cause.span;
                        let guar =
                            if span.is_dummy() ||
                                    #[allow(non_exhaustive_omitted_patterns)] match obligation.cause.code()
                                        {
                                        ObligationCauseCode::CheckAssociatedTypeBounds { .. } =>
                                            true,
                                        _ => false,
                                    } {
                                tcx.dcx().span_delayed_bug(span,
                                    ::alloc::__export::must_use({
                                            ::alloc::fmt::format(format_args!("projection from non-dyn-compatible trait `{0}`",
                                                    tcx.def_path_str(def_id)))
                                        }))
                            } else {
                                let violations = tcx.dyn_compatibility_violations(def_id);
                                report_dyn_incompatibility(tcx, span, None, def_id,
                                        &violations).emit_err()
                            };
                        return Ok(Projected::Progress(Progress::error_for_term(tcx,
                                        obligation.predicate, guar)));
                    }
                }
            }
            let mut candidates = ProjectionCandidateSet::None;
            assemble_candidates_from_param_env(selcx, obligation,
                &mut candidates);
            assemble_candidates_from_trait_def(selcx, obligation,
                &mut candidates);
            assemble_candidates_from_object_ty(selcx, obligation,
                &mut candidates);
            if let ProjectionCandidateSet::Single(ProjectionCandidate::Object(_))
                    = candidates
                {} else {
                assemble_candidates_from_impls(selcx, obligation,
                    &mut candidates);
            };
            match candidates {
                ProjectionCandidateSet::Single(candidate) => {
                    confirm_candidate(selcx, obligation, candidate)
                }
                ProjectionCandidateSet::None => {
                    let tcx = selcx.tcx();
                    let term =
                        obligation.predicate.to_term(tcx, ty::IsRigid::No);
                    Ok(Projected::NoProgress(term))
                }
                ProjectionCandidateSet::Error(e) =>
                    Err(ProjectionError::TraitSelectionError(e)),
                ProjectionCandidateSet::Ambiguous =>
                    Err(ProjectionError::TooManyCandidates),
            }
        }
    }
}#[instrument(level = "info", skip(selcx))]
694fn project<'cx, 'tcx>(
695    selcx: &mut SelectionContext<'cx, 'tcx>,
696    obligation: &ProjectionTermObligation<'tcx>,
697) -> Result<Projected<'tcx>, ProjectionError<'tcx>> {
698    if !selcx.tcx().recursion_limit().value_within_limit(obligation.recursion_depth) {
699        // This should really be an immediate error, but some existing code
700        // relies on being able to recover from this.
701        return Err(ProjectionError::TraitSelectionError(SelectionError::Overflow(
702            OverflowError::Canonical,
703        )));
704    }
705
706    // We can still compute a projection type when there are only region errors,
707    // but type/const errors require early return.
708    if let Err(guar) = obligation.predicate.non_region_error_reported() {
709        return Ok(Projected::Progress(Progress::error_for_term(
710            selcx.tcx(),
711            obligation.predicate,
712            guar,
713        )));
714    }
715
716    // `<dyn Trait>::Name` is only valid when `Trait` is dyn-compatible.
717    // If it isn't, create an error at the projection site and return a tainted error term.
718    let self_ty = selcx.infcx.shallow_resolve(obligation.predicate.self_ty());
719    if let ty::Dynamic(data, ..) = self_ty.kind() {
720        if let Some(def_id) = data.principal_def_id() {
721            let tcx = selcx.tcx();
722            // Delaying a bug is fine here:
723            // - In case of a dymmy span, we are in a canonical query.
724            // - `CheckAssociatedTypeBounds` means that the trait object is part of the trait's item bounds
725            //   or the impl's associated type; both are checked at their own definition
726            //   where the error is already reported with a better span.
727            if !tcx.is_dyn_compatible(def_id) {
728                let span = obligation.cause.span;
729                let guar = if span.is_dummy()
730                    || matches!(
731                        obligation.cause.code(),
732                        ObligationCauseCode::CheckAssociatedTypeBounds { .. }
733                    ) {
734                    tcx.dcx().span_delayed_bug(
735                        span,
736                        format!(
737                            "projection from non-dyn-compatible trait `{}`",
738                            tcx.def_path_str(def_id)
739                        ),
740                    )
741                } else {
742                    let violations = tcx.dyn_compatibility_violations(def_id);
743                    report_dyn_incompatibility(tcx, span, None, def_id, &violations).emit_err()
744                };
745                return Ok(Projected::Progress(Progress::error_for_term(
746                    tcx,
747                    obligation.predicate,
748                    guar,
749                )));
750            }
751        }
752    }
753
754    let mut candidates = ProjectionCandidateSet::None;
755
756    // Make sure that the following procedures are kept in order. ParamEnv
757    // needs to be first because it has highest priority, and Select checks
758    // the return value of push_candidate which assumes it's ran at last.
759    assemble_candidates_from_param_env(selcx, obligation, &mut candidates);
760
761    assemble_candidates_from_trait_def(selcx, obligation, &mut candidates);
762
763    assemble_candidates_from_object_ty(selcx, obligation, &mut candidates);
764
765    if let ProjectionCandidateSet::Single(ProjectionCandidate::Object(_)) = candidates {
766        // Avoid normalization cycle from selection (see
767        // `assemble_candidates_from_object_ty`).
768        // FIXME(lazy_normalization): Lazy normalization should save us from
769        // having to special case this.
770    } else {
771        assemble_candidates_from_impls(selcx, obligation, &mut candidates);
772    };
773
774    match candidates {
775        ProjectionCandidateSet::Single(candidate) => {
776            confirm_candidate(selcx, obligation, candidate)
777        }
778        ProjectionCandidateSet::None => {
779            let tcx = selcx.tcx();
780            let term = obligation.predicate.to_term(tcx, ty::IsRigid::No);
781            Ok(Projected::NoProgress(term))
782        }
783        // Error occurred while trying to processing impls.
784        ProjectionCandidateSet::Error(e) => Err(ProjectionError::TraitSelectionError(e)),
785        // Inherent ambiguity that prevents us from even enumerating the
786        // candidates.
787        ProjectionCandidateSet::Ambiguous => Err(ProjectionError::TooManyCandidates),
788    }
789}
790
791/// The first thing we have to do is scan through the parameter
792/// environment to see whether there are any projection predicates
793/// there that can answer this question.
794fn assemble_candidates_from_param_env<'cx, 'tcx>(
795    selcx: &mut SelectionContext<'cx, 'tcx>,
796    obligation: &ProjectionTermObligation<'tcx>,
797    candidate_set: &mut ProjectionCandidateSet<'tcx>,
798) {
799    assemble_candidates_from_projection_clauses(
800        selcx,
801        obligation,
802        candidate_set,
803        ProjectionCandidate::ParamEnv,
804        obligation
805            .param_env
806            .caller_bounds()
807            .non_trait_clauses()
808            .iter()
809            .filter_map(|i| i.as_projection_clause()),
810        false,
811    );
812}
813
814/// In the case of a nested projection like `<<A as Foo>::FooT as Bar>::BarT`, we may find
815/// that the definition of `Foo` has some clues:
816///
817/// ```ignore (illustrative)
818/// trait Foo {
819///     type FooT : Bar<BarT=i32>
820/// }
821/// ```
822///
823/// Here, for example, we could conclude that the result is `i32`.
824fn assemble_candidates_from_trait_def<'cx, 'tcx>(
825    selcx: &mut SelectionContext<'cx, 'tcx>,
826    obligation: &ProjectionTermObligation<'tcx>,
827    candidate_set: &mut ProjectionCandidateSet<'tcx>,
828) {
829    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs:829",
                        "rustc_trait_selection::traits::project",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs"),
                        ::tracing_core::__macro_support::Option::Some(829u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::project"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("assemble_candidates_from_trait_def(..)")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("assemble_candidates_from_trait_def(..)");
830    let mut ambiguous = false;
831    let _ = selcx.for_each_item_bound(
832        obligation.predicate.self_ty(),
833        |selcx, clause, _, _| {
834            let Some(clause) = clause.as_projection_clause() else {
835                return ControlFlow::Continue(());
836            };
837            if clause.item_def_id() != obligation.predicate.expect_projection_def_id() {
838                return ControlFlow::Continue(());
839            }
840
841            let is_match =
842                selcx.infcx.probe(|_| selcx.match_projection_projections(obligation, clause, true));
843
844            match is_match {
845                ProjectionMatchesProjection::Yes => {
846                    candidate_set.push_candidate(ProjectionCandidate::TraitDef(clause));
847
848                    if !obligation.predicate.has_non_region_infer() {
849                        // HACK: Pick the first trait def candidate for a fully
850                        // inferred predicate. This is to allow duplicates that
851                        // differ only in normalization.
852                        return ControlFlow::Break(());
853                    }
854                }
855                ProjectionMatchesProjection::Ambiguous => {
856                    candidate_set.mark_ambiguous();
857                }
858                ProjectionMatchesProjection::No => {}
859            }
860
861            ControlFlow::Continue(())
862        },
863        // `ProjectionCandidateSet` is borrowed in the above closure,
864        // so just mark ambiguous outside of the closure.
865        || ambiguous = true,
866    );
867
868    if ambiguous {
869        candidate_set.mark_ambiguous();
870    }
871}
872
873/// In the case of a trait object like
874/// `<dyn Iterator<Item = ()> as Iterator>::Item` we can use the existential
875/// predicate in the trait object.
876///
877/// We don't go through the select candidate for these bounds to avoid cycles:
878/// In the above case, `dyn Iterator<Item = ()>: Iterator` would create a
879/// nested obligation of `<dyn Iterator<Item = ()> as Iterator>::Item: Sized`,
880/// this then has to be normalized without having to prove
881/// `dyn Iterator<Item = ()>: Iterator` again.
882fn assemble_candidates_from_object_ty<'cx, 'tcx>(
883    selcx: &mut SelectionContext<'cx, 'tcx>,
884    obligation: &ProjectionTermObligation<'tcx>,
885    candidate_set: &mut ProjectionCandidateSet<'tcx>,
886) {
887    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs:887",
                        "rustc_trait_selection::traits::project",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs"),
                        ::tracing_core::__macro_support::Option::Some(887u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::project"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("assemble_candidates_from_object_ty(..)")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("assemble_candidates_from_object_ty(..)");
888
889    let tcx = selcx.tcx();
890
891    let self_ty = obligation.predicate.self_ty();
892    let object_ty = selcx.infcx.shallow_resolve(self_ty);
893    let data = match object_ty.kind() {
894        ty::Dynamic(data, ..) => data,
895        ty::Infer(ty::TyVar(_)) => {
896            // If the self-type is an inference variable, then it MAY wind up
897            // being an object type, so induce an ambiguity.
898            candidate_set.mark_ambiguous();
899            return;
900        }
901        _ => return,
902    };
903
904    // Projecting `dyn Trait` is only valid when `Trait` is dyn-compatible.
905    if data.principal_def_id().is_some_and(|def_id| !tcx.is_dyn_compatible(def_id)) {
906        return;
907    }
908
909    let env_predicates = data
910        .projection_bounds()
911        .filter(|bound| bound.item_def_id() == obligation.predicate.expect_projection_def_id())
912        .map(|p| p.with_self_ty(tcx, object_ty).upcast(tcx));
913
914    assemble_candidates_from_clauses(
915        selcx,
916        obligation,
917        candidate_set,
918        ProjectionCandidate::Object,
919        env_predicates,
920        false,
921    );
922}
923
924fn assemble_candidates_from_clauses<'cx, 'tcx>(
925    selcx: &mut SelectionContext<'cx, 'tcx>,
926    obligation: &ProjectionTermObligation<'tcx>,
927    candidate_set: &mut ProjectionCandidateSet<'tcx>,
928    ctor: fn(ty::PolyProjectionClause<'tcx>) -> ProjectionCandidate<'tcx>,
929    env_clauses: impl Iterator<Item = ty::Clause<'tcx>>,
930    potentially_unnormalized_candidates: bool,
931) {
932    assemble_candidates_from_projection_clauses(
933        selcx,
934        obligation,
935        candidate_set,
936        ctor,
937        env_clauses.filter_map(|i| i.as_projection_clause()),
938        potentially_unnormalized_candidates,
939    );
940}
941
942{}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("assemble_candidates_from_projection_clauses",
                                    "rustc_trait_selection::traits::project",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs"),
                                    ::tracing_core::__macro_support::Option::Some(942u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::project"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("obligation")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("obligation");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligation)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let infcx = selcx.infcx;
            let drcx = DeepRejectCtxt::relate_rigid_rigid(selcx.tcx());
            for clause in env_clauses {
                if clause.item_def_id() !=
                        obligation.predicate.expect_projection_def_id() {
                    continue;
                }
                if !drcx.args_may_unify(obligation.predicate.args,
                            clause.skip_binder().projection_term.args) {
                    continue;
                }
                let is_match =
                    infcx.probe(|_|
                            {
                                selcx.match_projection_projections(obligation, clause,
                                    potentially_unnormalized_candidates)
                            });
                match is_match {
                    ProjectionMatchesProjection::Yes => {
                        candidate_set.push_candidate(ctor(clause));
                        if potentially_unnormalized_candidates &&
                                !obligation.predicate.has_non_region_infer() {
                            return;
                        }
                    }
                    ProjectionMatchesProjection::Ambiguous => {
                        candidate_set.mark_ambiguous();
                    }
                    ProjectionMatchesProjection::No => {}
                }
            }
        }
    }
}#[instrument(
943    level = "debug",
944    skip(selcx, candidate_set, ctor, env_clauses, potentially_unnormalized_candidates)
945)]
946fn assemble_candidates_from_projection_clauses<'cx, 'tcx>(
947    selcx: &mut SelectionContext<'cx, 'tcx>,
948    obligation: &ProjectionTermObligation<'tcx>,
949    candidate_set: &mut ProjectionCandidateSet<'tcx>,
950    ctor: fn(ty::PolyProjectionClause<'tcx>) -> ProjectionCandidate<'tcx>,
951    env_clauses: impl Iterator<Item = ty::PolyProjectionClause<'tcx>>,
952    potentially_unnormalized_candidates: bool,
953) {
954    let infcx = selcx.infcx;
955    let drcx = DeepRejectCtxt::relate_rigid_rigid(selcx.tcx());
956    for clause in env_clauses {
957        if clause.item_def_id() != obligation.predicate.expect_projection_def_id() {
958            continue;
959        }
960
961        if !drcx
962            .args_may_unify(obligation.predicate.args, clause.skip_binder().projection_term.args)
963        {
964            continue;
965        }
966
967        let is_match = infcx.probe(|_| {
968            selcx.match_projection_projections(
969                obligation,
970                clause,
971                potentially_unnormalized_candidates,
972            )
973        });
974
975        match is_match {
976            ProjectionMatchesProjection::Yes => {
977                candidate_set.push_candidate(ctor(clause));
978
979                if potentially_unnormalized_candidates
980                    && !obligation.predicate.has_non_region_infer()
981                {
982                    // HACK: Pick the first trait def candidate for a fully
983                    // inferred predicate. This is to allow duplicates that
984                    // differ only in normalization.
985                    return;
986                }
987            }
988            ProjectionMatchesProjection::Ambiguous => {
989                candidate_set.mark_ambiguous();
990            }
991            ProjectionMatchesProjection::No => {}
992        }
993    }
994}
995
996{}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("assemble_candidates_from_impls",
                                    "rustc_trait_selection::traits::project",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs"),
                                    ::tracing_core::__macro_support::Option::Some(996u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::project"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set_all(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let trait_ref = obligation.predicate.trait_ref(selcx.tcx());
            let trait_obligation = obligation.with(selcx.tcx(), trait_ref);
            let _ =
                selcx.infcx.commit_if_ok(|_|
                        {
                            let impl_source =
                                match selcx.select(&trait_obligation) {
                                    Ok(Some(impl_source)) => impl_source,
                                    Ok(None) => {
                                        candidate_set.mark_ambiguous();
                                        return Err(());
                                    }
                                    Err(e) => {
                                        {
                                            use ::tracing::__macro_support::Callsite as _;
                                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                                {
                                                    static META: ::tracing::Metadata<'static> =
                                                        {
                                                            ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs:1014",
                                                                "rustc_trait_selection::traits::project",
                                                                ::tracing::Level::DEBUG,
                                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs"),
                                                                ::tracing_core::__macro_support::Option::Some(1014u32),
                                                                ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::project"),
                                                                ::tracing_core::field::FieldSet::new(&["message",
                                                                                {
                                                                                    const NAME:
                                                                                        ::tracing::__macro_support::FieldName<{
                                                                                            ::tracing::__macro_support::FieldName::len("error")
                                                                                        }> =
                                                                                        ::tracing::__macro_support::FieldName::new("error");
                                                                                    NAME.as_str()
                                                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                                ::tracing::metadata::Kind::EVENT)
                                                        };
                                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                                };
                                            let enabled =
                                                ::tracing::Level::DEBUG <=
                                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                        ::tracing::Level::DEBUG <=
                                                            ::tracing::level_filters::LevelFilter::current() &&
                                                    {
                                                        let interest = __CALLSITE.interest();
                                                        !interest.is_never() &&
                                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                                interest)
                                                    };
                                            if enabled {
                                                (|value_set: ::tracing::field::ValueSet|
                                                            {
                                                                let meta = __CALLSITE.metadata();
                                                                ::tracing::Event::dispatch(meta, &value_set);
                                                                ;
                                                            })({
                                                        #[allow(unused_imports)]
                                                        use ::tracing::field::{debug, display, Value};
                                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("selection error")
                                                                                    as &dyn ::tracing::field::Value)),
                                                                        (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&e)
                                                                                    as &dyn ::tracing::field::Value))])
                                                    });
                                            } else { ; }
                                        };
                                        candidate_set.mark_error(e);
                                        return Err(());
                                    }
                                };
                            let eligible =
                                match &impl_source {
                                    ImplSource::UserDefined(impl_data) => {
                                        match specialization_graph::assoc_def(selcx.tcx(),
                                                impl_data.impl_def_id,
                                                obligation.predicate.expect_projection_def_id()) {
                                            Ok(node_item) => {
                                                if node_item.is_final() {
                                                    true
                                                } else {
                                                    match selcx.typing_mode() {
                                                        TypingMode::Typeck { .. } |
                                                            TypingMode::PostTypeckThroughBorrowck { .. } |
                                                            TypingMode::Reflection | TypingMode::PostBorrowck { .. } =>
                                                            {
                                                            {
                                                                use ::tracing::__macro_support::Callsite as _;
                                                                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                                                    {
                                                                        static META: ::tracing::Metadata<'static> =
                                                                            {
                                                                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs:1063",
                                                                                    "rustc_trait_selection::traits::project",
                                                                                    ::tracing::Level::DEBUG,
                                                                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs"),
                                                                                    ::tracing_core::__macro_support::Option::Some(1063u32),
                                                                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::project"),
                                                                                    ::tracing_core::field::FieldSet::new(&["message",
                                                                                                    {
                                                                                                        const NAME:
                                                                                                            ::tracing::__macro_support::FieldName<{
                                                                                                                ::tracing::__macro_support::FieldName::len("assoc_ty")
                                                                                                            }> =
                                                                                                            ::tracing::__macro_support::FieldName::new("assoc_ty");
                                                                                                        NAME.as_str()
                                                                                                    },
                                                                                                    {
                                                                                                        const NAME:
                                                                                                            ::tracing::__macro_support::FieldName<{
                                                                                                                ::tracing::__macro_support::FieldName::len("obligation.predicate")
                                                                                                            }> =
                                                                                                            ::tracing::__macro_support::FieldName::new("obligation.predicate");
                                                                                                        NAME.as_str()
                                                                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                                                    ::tracing::metadata::Kind::EVENT)
                                                                            };
                                                                        ::tracing::callsite::DefaultCallsite::new(&META)
                                                                    };
                                                                let enabled =
                                                                    ::tracing::Level::DEBUG <=
                                                                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                                            ::tracing::Level::DEBUG <=
                                                                                ::tracing::level_filters::LevelFilter::current() &&
                                                                        {
                                                                            let interest = __CALLSITE.interest();
                                                                            !interest.is_never() &&
                                                                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                                                    interest)
                                                                        };
                                                                if enabled {
                                                                    (|value_set: ::tracing::field::ValueSet|
                                                                                {
                                                                                    let meta = __CALLSITE.metadata();
                                                                                    ::tracing::Event::dispatch(meta, &value_set);
                                                                                    ;
                                                                                })({
                                                                            #[allow(unused_imports)]
                                                                            use ::tracing::field::{debug, display, Value};
                                                                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("not eligible due to default")
                                                                                                        as &dyn ::tracing::field::Value)),
                                                                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&selcx.tcx().def_path_str(node_item.item.def_id))
                                                                                                        as &dyn ::tracing::field::Value)),
                                                                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligation.predicate)
                                                                                                        as &dyn ::tracing::field::Value))])
                                                                        });
                                                                } else { ; }
                                                            };
                                                            false
                                                        }
                                                        TypingMode::PostAnalysis | TypingMode::Codegen => {
                                                            let poly_trait_ref =
                                                                selcx.infcx.deeply_resolve_ignoring_regions(trait_ref);
                                                            !poly_trait_ref.still_further_specializable()
                                                        }
                                                        TypingMode::Coherence => {
                                                            {
                                                                ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
                                                                        format_args!("old solver coherence")));
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            Err(ErrorGuaranteed { .. }) => true,
                                        }
                                    }
                                    ImplSource::Builtin(BuiltinImplSource::Misc |
                                        BuiltinImplSource::Trivial, _) => {
                                        let self_ty =
                                            selcx.infcx.shallow_resolve(obligation.predicate.self_ty());
                                        let tcx = selcx.tcx();
                                        match selcx.tcx().as_lang_item(trait_ref.def_id) {
                                            Some(LangItem::Coroutine | LangItem::Future |
                                                LangItem::Iterator | LangItem::AsyncIterator |
                                                LangItem::Field | LangItem::Fn | LangItem::FnMut |
                                                LangItem::FnOnce | LangItem::AsyncFn | LangItem::AsyncFnMut
                                                | LangItem::AsyncFnOnce) => true,
                                            Some(LangItem::AsyncFnKindHelper) => {
                                                if obligation.predicate.args.type_at(0).is_ty_var() ||
                                                            obligation.predicate.args.type_at(4).is_ty_var() ||
                                                        obligation.predicate.args.type_at(5).is_ty_var() {
                                                    candidate_set.mark_ambiguous();
                                                    true
                                                } else {
                                                    obligation.predicate.args.type_at(0).to_opt_closure_kind().is_some()
                                                        &&
                                                        obligation.predicate.args.type_at(1).to_opt_closure_kind().is_some()
                                                }
                                            }
                                            Some(LangItem::DiscriminantKind) =>
                                                match self_ty.kind() {
                                                    ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) |
                                                        ty::Float(_) | ty::Adt(..) | ty::Foreign(_) | ty::Str |
                                                        ty::Array(..) | ty::Pat(..) | ty::Slice(_) | ty::RawPtr(..)
                                                        | ty::Ref(..) | ty::FnDef(..) | ty::FnPtr(..) |
                                                        ty::Dynamic(..) | ty::Closure(..) | ty::CoroutineClosure(..)
                                                        | ty::Coroutine(..) | ty::CoroutineWitness(..) | ty::Never |
                                                        ty::Tuple(..) |
                                                        ty::Infer(ty::InferTy::IntVar(_) |
                                                        ty::InferTy::FloatVar(..)) => true,
                                                    ty::UnsafeBinder(_) => {
                                                        ::core::panicking::panic_fmt(format_args!("not implemented: {0}",
                                                                format_args!("FIXME(unsafe_binder)")));
                                                    }
                                                    ty::Param(_) | ty::Alias(..) | ty::Bound(..) |
                                                        ty::Placeholder(..) | ty::Infer(..) | ty::Error(_) => false,
                                                    ty::View(..) =>
                                                        ::core::panicking::unimplemented_default_msg(),
                                                },
                                            Some(LangItem::PointeeTrait) => {
                                                let tail =
                                                    selcx.tcx().struct_tail_raw(self_ty, &obligation.cause,
                                                        |ty|
                                                            {
                                                                normalize_with_depth(selcx, obligation.param_env,
                                                                        obligation.cause.clone(), obligation.recursion_depth + 1,
                                                                        ty).value
                                                            }, || {});
                                                match tail.kind() {
                                                    ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) |
                                                        ty::Float(_) | ty::Str | ty::Array(..) | ty::Pat(..) |
                                                        ty::Slice(_) | ty::RawPtr(..) | ty::Ref(..) | ty::FnDef(..)
                                                        | ty::FnPtr(..) | ty::Dynamic(..) | ty::Closure(..) |
                                                        ty::CoroutineClosure(..) | ty::Coroutine(..) |
                                                        ty::CoroutineWitness(..) | ty::Never | ty::Foreign(_) |
                                                        ty::Adt(..) | ty::Tuple(..) | ty::View(_, _, _) |
                                                        ty::Infer(ty::InferTy::IntVar(_) |
                                                        ty::InferTy::FloatVar(..)) | ty::Error(..) => true,
                                                    ty::Param(_) | ty::Alias(..) if
                                                        self_ty != tail ||
                                                            selcx.infcx.predicate_must_hold_modulo_regions(&obligation.with(selcx.tcx(),
                                                                        ty::TraitRef::new(selcx.tcx(),
                                                                            selcx.tcx().require_lang_item(LangItem::Sized,
                                                                                obligation.cause.span), [self_ty]))) => {
                                                        true
                                                    }
                                                    ty::UnsafeBinder(_) => {
                                                        ::core::panicking::panic_fmt(format_args!("not implemented: {0}",
                                                                format_args!("FIXME(unsafe_binder)")));
                                                    }
                                                    ty::Param(_) | ty::Alias(..) | ty::Bound(..) |
                                                        ty::Placeholder(..) | ty::Infer(..) => {
                                                        if tail.has_infer_types() {
                                                            candidate_set.mark_ambiguous();
                                                        }
                                                        false
                                                    }
                                                }
                                            }
                                            _ if tcx.trait_is_auto(trait_ref.def_id) => {
                                                tcx.dcx().span_delayed_bug(tcx.def_span(obligation.predicate.expect_projection_def_id()),
                                                    "associated types not allowed on auto traits");
                                                false
                                            }
                                            _ => {
                                                ::rustc_span::macros::bug_impl(None,
                                                    format_args!("unexpected builtin trait with associated type: {0:?}",
                                                        trait_ref), Location::caller())
                                            }
                                        }
                                    }
                                    ImplSource::Param(..) => { false }
                                    ImplSource::Builtin(BuiltinImplSource::Object { .. }, _) =>
                                        {
                                        false
                                    }
                                    ImplSource::Builtin(BuiltinImplSource::TraitUpcasting { ..
                                        }, _) => {
                                        selcx.tcx().dcx().span_delayed_bug(obligation.cause.span,
                                            ::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!("Cannot project an associated type from `{0:?}`",
                                                            impl_source))
                                                }));
                                        return Err(());
                                    }
                                };
                            if eligible {
                                if candidate_set.push_candidate(ProjectionCandidate::Select(impl_source))
                                    {
                                    Ok(())
                                } else { Err(()) }
                            } else { Err(()) }
                        });
        }
    }
}#[instrument(level = "debug", skip(selcx, obligation, candidate_set))]
997fn assemble_candidates_from_impls<'cx, 'tcx>(
998    selcx: &mut SelectionContext<'cx, 'tcx>,
999    obligation: &ProjectionTermObligation<'tcx>,
1000    candidate_set: &mut ProjectionCandidateSet<'tcx>,
1001) {
1002    // If we are resolving `<T as TraitRef<...>>::Item == Type`,
1003    // start out by selecting the predicate `T as TraitRef<...>`:
1004    let trait_ref = obligation.predicate.trait_ref(selcx.tcx());
1005    let trait_obligation = obligation.with(selcx.tcx(), trait_ref);
1006    let _ = selcx.infcx.commit_if_ok(|_| {
1007        let impl_source = match selcx.select(&trait_obligation) {
1008            Ok(Some(impl_source)) => impl_source,
1009            Ok(None) => {
1010                candidate_set.mark_ambiguous();
1011                return Err(());
1012            }
1013            Err(e) => {
1014                debug!(error = ?e, "selection error");
1015                candidate_set.mark_error(e);
1016                return Err(());
1017            }
1018        };
1019
1020        let eligible = match &impl_source {
1021            ImplSource::UserDefined(impl_data) => {
1022                // We have to be careful when projecting out of an
1023                // impl because of specialization. If we are not in
1024                // codegen (i.e., `TypingMode` is not `PostAnalysis`), and the
1025                // impl's type is declared as default, then we disable
1026                // projection (even if the trait ref is fully
1027                // monomorphic). In the case where trait ref is not
1028                // fully monomorphic (i.e., includes type parameters),
1029                // this is because those type parameters may
1030                // ultimately be bound to types from other crates that
1031                // may have specialized impls we can't see. In the
1032                // case where the trait ref IS fully monomorphic, this
1033                // is a policy decision that we made in the RFC in
1034                // order to preserve flexibility for the crate that
1035                // defined the specializable impl to specialize later
1036                // for existing types.
1037                //
1038                // In either case, we handle this by not adding a
1039                // candidate for an impl if it contains a `default`
1040                // type.
1041                //
1042                // NOTE: This should be kept in sync with the similar code in
1043                // `rustc_ty_utils::instance::resolve_associated_item()`.
1044                match specialization_graph::assoc_def(
1045                    selcx.tcx(),
1046                    impl_data.impl_def_id,
1047                    obligation.predicate.expect_projection_def_id(),
1048                ) {
1049                    Ok(node_item) => {
1050                        if node_item.is_final() {
1051                            // Non-specializable items are always projectable.
1052                            true
1053                        } else {
1054                            // Only reveal a specializable default if we're past type-checking
1055                            // and the obligation is monomorphic, otherwise passes such as
1056                            // transmute checking and polymorphic MIR optimizations could
1057                            // get a result which isn't correct for all monomorphizations.
1058                            match selcx.typing_mode() {
1059                                TypingMode::Typeck { .. }
1060                                | TypingMode::PostTypeckThroughBorrowck { .. }
1061                                | TypingMode::Reflection
1062                                | TypingMode::PostBorrowck { .. } => {
1063                                    debug!(
1064                                        assoc_ty = ?selcx.tcx().def_path_str(node_item.item.def_id),
1065                                        ?obligation.predicate,
1066                                        "not eligible due to default",
1067                                    );
1068                                    false
1069                                }
1070                                TypingMode::PostAnalysis | TypingMode::Codegen => {
1071                                    // NOTE(eddyb) inference variables can resolve to parameters, so
1072                                    // assume `poly_trait_ref` isn't monomorphic, if it contains any.
1073                                    let poly_trait_ref =
1074                                        selcx.infcx.deeply_resolve_ignoring_regions(trait_ref);
1075                                    !poly_trait_ref.still_further_specializable()
1076                                }
1077                                TypingMode::Coherence => {
1078                                    unreachable!("old solver coherence")
1079                                }
1080                            }
1081                        }
1082                    }
1083                    // Always project `ErrorGuaranteed`, since this will just help
1084                    // us propagate `TyKind::Error` around which suppresses ICEs
1085                    // and spurious, unrelated inference errors.
1086                    Err(ErrorGuaranteed { .. }) => true,
1087                }
1088            }
1089            ImplSource::Builtin(BuiltinImplSource::Misc | BuiltinImplSource::Trivial, _) => {
1090                // While a builtin impl may be known to exist, the associated type may not yet
1091                // be known. Any type with multiple potential associated types is therefore
1092                // not eligible.
1093                let self_ty = selcx.infcx.shallow_resolve(obligation.predicate.self_ty());
1094
1095                let tcx = selcx.tcx();
1096                match selcx.tcx().as_lang_item(trait_ref.def_id) {
1097                    Some(
1098                        LangItem::Coroutine
1099                        | LangItem::Future
1100                        | LangItem::Iterator
1101                        | LangItem::AsyncIterator
1102                        | LangItem::Field
1103                        | LangItem::Fn
1104                        | LangItem::FnMut
1105                        | LangItem::FnOnce
1106                        | LangItem::AsyncFn
1107                        | LangItem::AsyncFnMut
1108                        | LangItem::AsyncFnOnce,
1109                    ) => true,
1110                    Some(LangItem::AsyncFnKindHelper) => {
1111                        // FIXME(async_closures): Validity constraints here could be cleaned up.
1112                        if obligation.predicate.args.type_at(0).is_ty_var()
1113                            || obligation.predicate.args.type_at(4).is_ty_var()
1114                            || obligation.predicate.args.type_at(5).is_ty_var()
1115                        {
1116                            candidate_set.mark_ambiguous();
1117                            true
1118                        } else {
1119                            obligation.predicate.args.type_at(0).to_opt_closure_kind().is_some()
1120                                && obligation
1121                                    .predicate
1122                                    .args
1123                                    .type_at(1)
1124                                    .to_opt_closure_kind()
1125                                    .is_some()
1126                        }
1127                    }
1128                    Some(LangItem::DiscriminantKind) => match self_ty.kind() {
1129                        ty::Bool
1130                        | ty::Char
1131                        | ty::Int(_)
1132                        | ty::Uint(_)
1133                        | ty::Float(_)
1134                        | ty::Adt(..)
1135                        | ty::Foreign(_)
1136                        | ty::Str
1137                        | ty::Array(..)
1138                        | ty::Pat(..)
1139                        | ty::Slice(_)
1140                        | ty::RawPtr(..)
1141                        | ty::Ref(..)
1142                        | ty::FnDef(..)
1143                        | ty::FnPtr(..)
1144                        | ty::Dynamic(..)
1145                        | ty::Closure(..)
1146                        | ty::CoroutineClosure(..)
1147                        | ty::Coroutine(..)
1148                        | ty::CoroutineWitness(..)
1149                        | ty::Never
1150                        | ty::Tuple(..)
1151                        // Integers and floats always have `u8` as their discriminant.
1152                        | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(..)) => true,
1153
1154                        ty::UnsafeBinder(_) => unimplemented!("FIXME(unsafe_binder)"),
1155
1156                        // type parameters, opaques, and unnormalized projections don't have
1157                        // a known discriminant and may need to be normalized further or rely
1158                        // on param env for discriminant projections
1159                        ty::Param(_)
1160                        | ty::Alias(..)
1161                        | ty::Bound(..)
1162                        | ty::Placeholder(..)
1163                        | ty::Infer(..)
1164                        | ty::Error(_) => false,
1165
1166                        // FIXME(scrabsha)
1167                        ty::View(..) => unimplemented!(),
1168                    },
1169                    Some(LangItem::PointeeTrait) => {
1170                        let tail = selcx.tcx().struct_tail_raw(
1171                            self_ty,
1172                            &obligation.cause,
1173                            |ty| {
1174                                // We throw away any obligations we get from this, since we normalize
1175                                // and confirm these obligations once again during confirmation
1176                                normalize_with_depth(
1177                                    selcx,
1178                                    obligation.param_env,
1179                                    obligation.cause.clone(),
1180                                    obligation.recursion_depth + 1,
1181                                    ty,
1182                                )
1183                                .value
1184                            },
1185                            || {},
1186                        );
1187
1188                        match tail.kind() {
1189                            ty::Bool
1190                            | ty::Char
1191                            | ty::Int(_)
1192                            | ty::Uint(_)
1193                            | ty::Float(_)
1194                            | ty::Str
1195                            | ty::Array(..)
1196                            | ty::Pat(..)
1197                            | ty::Slice(_)
1198                            | ty::RawPtr(..)
1199                            | ty::Ref(..)
1200                            | ty::FnDef(..)
1201                            | ty::FnPtr(..)
1202                            | ty::Dynamic(..)
1203                            | ty::Closure(..)
1204                            | ty::CoroutineClosure(..)
1205                            | ty::Coroutine(..)
1206                            | ty::CoroutineWitness(..)
1207                            | ty::Never
1208                            // Extern types have unit metadata, according to RFC 2850
1209                            | ty::Foreign(_)
1210                            // If returned by `struct_tail` this is a unit struct
1211                            // without any fields, or not a struct, and therefore is Sized.
1212                            | ty::Adt(..)
1213                            // If returned by `struct_tail` this is the empty tuple.
1214                            | ty::Tuple(..)
1215                            // FIXME(scrabsha): i guess view types behave like foreign types here?
1216                            | ty::View(_, _, _)
1217                            // Integers and floats are always Sized, and so have unit type metadata.
1218                            | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(..))
1219                            // This happens if we reach the recursion limit when finding the struct tail.
1220                            | ty::Error(..) => true,
1221
1222                            // We normalize from `Wrapper<Tail>::Metadata` to `Tail::Metadata` if able.
1223                            // Otherwise, type parameters, opaques, and unnormalized projections have
1224                            // unit metadata if they're known (e.g. by the param_env) to be sized.
1225                            ty::Param(_) | ty::Alias(..)
1226                                if self_ty != tail
1227                                    || selcx.infcx.predicate_must_hold_modulo_regions(
1228                                        &obligation.with(
1229                                            selcx.tcx(),
1230                                            ty::TraitRef::new(
1231                                                selcx.tcx(),
1232                                                selcx.tcx().require_lang_item(
1233                                                    LangItem::Sized,
1234                                                    obligation.cause.span,
1235                                                ),
1236                                                [self_ty],
1237                                            ),
1238                                        ),
1239                                    ) =>
1240                            {
1241                                true
1242                            }
1243
1244                            ty::UnsafeBinder(_) => unimplemented!("FIXME(unsafe_binder)"),
1245
1246                            // FIXME(compiler-errors): are Bound and Placeholder types ever known sized?
1247                            ty::Param(_)
1248                            | ty::Alias(..)
1249                            | ty::Bound(..)
1250                            | ty::Placeholder(..)
1251                            | ty::Infer(..) => {
1252                                if tail.has_infer_types() {
1253                                    candidate_set.mark_ambiguous();
1254                                }
1255                                false
1256                            }
1257                        }
1258                    }
1259                    _ if tcx.trait_is_auto(trait_ref.def_id) => {
1260                        tcx.dcx().span_delayed_bug(
1261                            tcx.def_span(obligation.predicate.expect_projection_def_id()),
1262                            "associated types not allowed on auto traits",
1263                        );
1264                        false
1265                    }
1266                    _ => {
1267                        bug!("unexpected builtin trait with associated type: {trait_ref:?}")
1268                    }
1269                }
1270            }
1271            ImplSource::Param(..) => {
1272                // This case tell us nothing about the value of an
1273                // associated type. Consider:
1274                //
1275                // ```
1276                // trait SomeTrait { type Foo; }
1277                // fn foo<T:SomeTrait>(...) { }
1278                // ```
1279                //
1280                // If the user writes `<T as SomeTrait>::Foo`, then the `T
1281                // : SomeTrait` binding does not help us decide what the
1282                // type `Foo` is (at least, not more specifically than
1283                // what we already knew).
1284                //
1285                // But wait, you say! What about an example like this:
1286                //
1287                // ```
1288                // fn bar<T:SomeTrait<Foo=usize>>(...) { ... }
1289                // ```
1290                //
1291                // Doesn't the `T : SomeTrait<Foo=usize>` predicate help
1292                // resolve `T::Foo`? And of course it does, but in fact
1293                // that single predicate is desugared into two predicates
1294                // in the compiler: a trait predicate (`T : SomeTrait`) and a
1295                // projection. And the projection where clause is handled
1296                // in `assemble_candidates_from_param_env`.
1297                false
1298            }
1299            ImplSource::Builtin(BuiltinImplSource::Object { .. }, _) => {
1300                // Handled by the `Object` projection candidate. See
1301                // `assemble_candidates_from_object_ty` for an explanation of
1302                // why we special case object types.
1303                false
1304            }
1305            ImplSource::Builtin(BuiltinImplSource::TraitUpcasting { .. }, _) => {
1306                // These traits have no associated types.
1307                selcx.tcx().dcx().span_delayed_bug(
1308                    obligation.cause.span,
1309                    format!("Cannot project an associated type from `{impl_source:?}`"),
1310                );
1311                return Err(());
1312            }
1313        };
1314
1315        if eligible {
1316            if candidate_set.push_candidate(ProjectionCandidate::Select(impl_source)) {
1317                Ok(())
1318            } else {
1319                Err(())
1320            }
1321        } else {
1322            Err(())
1323        }
1324    });
1325}
1326
1327// FIXME(mgca): While this supports constants, it is only used for types by default right now
1328fn confirm_candidate<'cx, 'tcx>(
1329    selcx: &mut SelectionContext<'cx, 'tcx>,
1330    obligation: &ProjectionTermObligation<'tcx>,
1331    candidate: ProjectionCandidate<'tcx>,
1332) -> Result<Projected<'tcx>, ProjectionError<'tcx>> {
1333    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs:1333",
                        "rustc_trait_selection::traits::project",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs"),
                        ::tracing_core::__macro_support::Option::Some(1333u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::project"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("obligation")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("obligation");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("candidate")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("candidate");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("confirm_candidate")
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligation)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&candidate)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?obligation, ?candidate, "confirm_candidate");
1334    let mut result = match candidate {
1335        ProjectionCandidate::ParamEnv(poly_projection)
1336        | ProjectionCandidate::Object(poly_projection) => Ok(Projected::Progress(
1337            confirm_param_env_candidate(selcx, obligation, poly_projection, false),
1338        )),
1339        ProjectionCandidate::TraitDef(poly_projection) => Ok(Projected::Progress(
1340            confirm_param_env_candidate(selcx, obligation, poly_projection, true),
1341        )),
1342        ProjectionCandidate::Select(impl_source) => {
1343            confirm_select_candidate(selcx, obligation, impl_source)
1344        }
1345    };
1346
1347    // When checking for cycle during evaluation, we compare predicates with
1348    // "syntactic" equality. Since normalization generally introduces a type
1349    // with new region variables, we need to resolve them to existing variables
1350    // when possible for this to work. See `auto-trait-projection-recursion.rs`
1351    // for a case where this matters.
1352    if let Ok(Projected::Progress(progress)) = &mut result
1353        && progress.term.has_infer_regions()
1354    {
1355        progress.term = selcx.infcx.deeply_resolve_via_unification_table(progress.term);
1356    }
1357
1358    result
1359}
1360
1361// FIXME(mgca): While this supports constants, it is only used for types by default right now
1362fn confirm_select_candidate<'cx, 'tcx>(
1363    selcx: &mut SelectionContext<'cx, 'tcx>,
1364    obligation: &ProjectionTermObligation<'tcx>,
1365    impl_source: Selection<'tcx>,
1366) -> Result<Projected<'tcx>, ProjectionError<'tcx>> {
1367    match impl_source {
1368        ImplSource::UserDefined(data) => confirm_impl_candidate(selcx, obligation, data),
1369        ImplSource::Builtin(BuiltinImplSource::Misc | BuiltinImplSource::Trivial, data) => {
1370            let tcx = selcx.tcx();
1371            let trait_def_id = obligation.predicate.trait_def_id(tcx);
1372            let progress = if tcx.is_lang_item(trait_def_id, LangItem::Coroutine) {
1373                confirm_coroutine_candidate(selcx, obligation, data)
1374            } else if tcx.is_lang_item(trait_def_id, LangItem::Future) {
1375                confirm_future_candidate(selcx, obligation, data)
1376            } else if tcx.is_lang_item(trait_def_id, LangItem::Iterator) {
1377                confirm_iterator_candidate(selcx, obligation, data)
1378            } else if tcx.is_lang_item(trait_def_id, LangItem::AsyncIterator) {
1379                confirm_async_iterator_candidate(selcx, obligation, data)
1380            } else if selcx.tcx().fn_trait_kind_from_def_id(trait_def_id).is_some() {
1381                if obligation.predicate.self_ty().is_closure()
1382                    || obligation.predicate.self_ty().is_coroutine_closure()
1383                {
1384                    confirm_closure_candidate(selcx, obligation, data)
1385                } else {
1386                    confirm_fn_pointer_candidate(selcx, obligation, data)
1387                }
1388            } else if selcx.tcx().async_fn_trait_kind_from_def_id(trait_def_id).is_some() {
1389                confirm_async_closure_candidate(selcx, obligation, data)
1390            } else if tcx.is_lang_item(trait_def_id, LangItem::AsyncFnKindHelper) {
1391                confirm_async_fn_kind_helper_candidate(selcx, obligation, data)
1392            } else {
1393                confirm_builtin_candidate(selcx, obligation, data)
1394            };
1395            Ok(Projected::Progress(progress))
1396        }
1397        ImplSource::Builtin(BuiltinImplSource::Object { .. }, _)
1398        | ImplSource::Param(..)
1399        | ImplSource::Builtin(BuiltinImplSource::TraitUpcasting { .. }, _) => {
1400            // we don't create Select candidates with this kind of resolution
1401            ::rustc_span::macros::bug_impl(Some(obligation.cause.span),
    format_args!("Cannot project an associated type from `{0:?}`",
        impl_source), Location::caller())span_bug!(
1402                obligation.cause.span,
1403                "Cannot project an associated type from `{:?}`",
1404                impl_source
1405            )
1406        }
1407    }
1408}
1409
1410fn confirm_coroutine_candidate<'cx, 'tcx>(
1411    selcx: &mut SelectionContext<'cx, 'tcx>,
1412    obligation: &ProjectionTermObligation<'tcx>,
1413    nested: PredicateObligations<'tcx>,
1414) -> Progress<'tcx> {
1415    let self_ty = selcx.infcx.shallow_resolve(obligation.predicate.self_ty());
1416    let ty::Coroutine(_, args) = self_ty.kind() else {
1417        {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("expected coroutine self type for built-in coroutine candidate, found {0}",
                self_ty)));
}unreachable!(
1418            "expected coroutine self type for built-in coroutine candidate, found {self_ty}"
1419        )
1420    };
1421    let coroutine_sig = Unnormalized::new_wip(args.as_coroutine().sig());
1422    let Normalized { value: coroutine_sig, obligations } = normalize_with_depth(
1423        selcx,
1424        obligation.param_env,
1425        obligation.cause.clone(),
1426        obligation.recursion_depth + 1,
1427        coroutine_sig,
1428    );
1429
1430    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs:1430",
                        "rustc_trait_selection::traits::project",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs"),
                        ::tracing_core::__macro_support::Option::Some(1430u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::project"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("obligation")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("obligation");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("coroutine_sig")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("coroutine_sig");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("obligations")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("obligations");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("confirm_coroutine_candidate")
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligation)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&coroutine_sig)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligations)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?obligation, ?coroutine_sig, ?obligations, "confirm_coroutine_candidate");
1431
1432    let tcx = selcx.tcx();
1433
1434    let coroutine_def_id = tcx.require_lang_item(LangItem::Coroutine, obligation.cause.span);
1435
1436    let (trait_ref, yield_ty, return_ty) = super::util::coroutine_trait_ref_and_outputs(
1437        tcx,
1438        coroutine_def_id,
1439        obligation.predicate.self_ty(),
1440        coroutine_sig,
1441    );
1442
1443    let def_id = obligation.predicate.expect_projection_def_id();
1444    let ty = if tcx.is_lang_item(def_id, LangItem::CoroutineReturn) {
1445        return_ty
1446    } else if tcx.is_lang_item(def_id, LangItem::CoroutineYield) {
1447        yield_ty
1448    } else {
1449        ::rustc_span::macros::bug_impl(Some(tcx.def_span(def_id)),
    format_args!("unexpected associated type: `Coroutine::{0}`",
        tcx.item_name(def_id)), Location::caller());span_bug!(
1450            tcx.def_span(def_id),
1451            "unexpected associated type: `Coroutine::{}`",
1452            tcx.item_name(def_id),
1453        );
1454    };
1455
1456    let predicate = ty::ProjectionClause {
1457        projection_term: obligation.predicate.with_args(tcx, trait_ref.args),
1458        term: ty.into(),
1459    };
1460
1461    confirm_param_env_candidate(selcx, obligation, ty::Binder::dummy(predicate), false)
1462        .with_addl_obligations(nested)
1463        .with_addl_obligations(obligations)
1464}
1465
1466fn confirm_future_candidate<'cx, 'tcx>(
1467    selcx: &mut SelectionContext<'cx, 'tcx>,
1468    obligation: &ProjectionTermObligation<'tcx>,
1469    nested: PredicateObligations<'tcx>,
1470) -> Progress<'tcx> {
1471    let self_ty = selcx.infcx.shallow_resolve(obligation.predicate.self_ty());
1472    let ty::Coroutine(_, args) = self_ty.kind() else {
1473        {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("expected coroutine self type for built-in async future candidate, found {0}",
                self_ty)));
}unreachable!(
1474            "expected coroutine self type for built-in async future candidate, found {self_ty}"
1475        )
1476    };
1477    let coroutine_sig = Unnormalized::new_wip(args.as_coroutine().sig());
1478    let Normalized { value: coroutine_sig, obligations } = normalize_with_depth(
1479        selcx,
1480        obligation.param_env,
1481        obligation.cause.clone(),
1482        obligation.recursion_depth + 1,
1483        coroutine_sig,
1484    );
1485
1486    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs:1486",
                        "rustc_trait_selection::traits::project",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs"),
                        ::tracing_core::__macro_support::Option::Some(1486u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::project"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("obligation")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("obligation");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("coroutine_sig")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("coroutine_sig");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("obligations")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("obligations");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("confirm_future_candidate")
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligation)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&coroutine_sig)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligations)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?obligation, ?coroutine_sig, ?obligations, "confirm_future_candidate");
1487
1488    let tcx = selcx.tcx();
1489    let fut_def_id = tcx.require_lang_item(LangItem::Future, obligation.cause.span);
1490
1491    let (trait_ref, return_ty) = super::util::future_trait_ref_and_outputs(
1492        tcx,
1493        fut_def_id,
1494        obligation.predicate.self_ty(),
1495        coroutine_sig,
1496    );
1497
1498    if true {
    {
        match (&tcx.associated_item(obligation.predicate.expect_projection_def_id()).name(),
                &sym::Output) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(
1499        tcx.associated_item(obligation.predicate.expect_projection_def_id()).name(),
1500        sym::Output
1501    );
1502
1503    let predicate = ty::ProjectionClause {
1504        projection_term: obligation.predicate.with_args(tcx, trait_ref.args),
1505        term: return_ty.into(),
1506    };
1507
1508    confirm_param_env_candidate(selcx, obligation, ty::Binder::dummy(predicate), false)
1509        .with_addl_obligations(nested)
1510        .with_addl_obligations(obligations)
1511}
1512
1513fn confirm_iterator_candidate<'cx, 'tcx>(
1514    selcx: &mut SelectionContext<'cx, 'tcx>,
1515    obligation: &ProjectionTermObligation<'tcx>,
1516    nested: PredicateObligations<'tcx>,
1517) -> Progress<'tcx> {
1518    let self_ty = selcx.infcx.shallow_resolve(obligation.predicate.self_ty());
1519    let ty::Coroutine(_, args) = self_ty.kind() else {
1520        {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("expected coroutine self type for built-in gen candidate, found {0}",
                self_ty)));
}unreachable!("expected coroutine self type for built-in gen candidate, found {self_ty}")
1521    };
1522    let gen_sig = Unnormalized::new_wip(args.as_coroutine().sig());
1523    let Normalized { value: gen_sig, obligations } = normalize_with_depth(
1524        selcx,
1525        obligation.param_env,
1526        obligation.cause.clone(),
1527        obligation.recursion_depth + 1,
1528        gen_sig,
1529    );
1530
1531    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs:1531",
                        "rustc_trait_selection::traits::project",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs"),
                        ::tracing_core::__macro_support::Option::Some(1531u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::project"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("obligation")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("obligation");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("gen_sig")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("gen_sig");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("obligations")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("obligations");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("confirm_iterator_candidate")
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligation)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&gen_sig)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligations)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?obligation, ?gen_sig, ?obligations, "confirm_iterator_candidate");
1532
1533    let tcx = selcx.tcx();
1534    let iter_def_id = tcx.require_lang_item(LangItem::Iterator, obligation.cause.span);
1535
1536    let (trait_ref, yield_ty) = super::util::iterator_trait_ref_and_outputs(
1537        tcx,
1538        iter_def_id,
1539        obligation.predicate.self_ty(),
1540        gen_sig,
1541    );
1542
1543    if true {
    {
        match (&tcx.associated_item(obligation.predicate.expect_projection_def_id()).name(),
                &sym::Item) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(
1544        tcx.associated_item(obligation.predicate.expect_projection_def_id()).name(),
1545        sym::Item
1546    );
1547
1548    let predicate = ty::ProjectionClause {
1549        projection_term: obligation.predicate.with_args(tcx, trait_ref.args),
1550        term: yield_ty.into(),
1551    };
1552
1553    confirm_param_env_candidate(selcx, obligation, ty::Binder::dummy(predicate), false)
1554        .with_addl_obligations(nested)
1555        .with_addl_obligations(obligations)
1556}
1557
1558fn confirm_async_iterator_candidate<'cx, 'tcx>(
1559    selcx: &mut SelectionContext<'cx, 'tcx>,
1560    obligation: &ProjectionTermObligation<'tcx>,
1561    nested: PredicateObligations<'tcx>,
1562) -> Progress<'tcx> {
1563    let ty::Coroutine(_, args) = selcx.infcx.shallow_resolve(obligation.predicate.self_ty()).kind()
1564    else {
1565        ::core::panicking::unreachable_default_msg()unreachable!()
1566    };
1567    let gen_sig = Unnormalized::new_wip(args.as_coroutine().sig());
1568    let Normalized { value: gen_sig, obligations } = normalize_with_depth(
1569        selcx,
1570        obligation.param_env,
1571        obligation.cause.clone(),
1572        obligation.recursion_depth + 1,
1573        gen_sig,
1574    );
1575
1576    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs:1576",
                        "rustc_trait_selection::traits::project",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs"),
                        ::tracing_core::__macro_support::Option::Some(1576u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::project"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("obligation")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("obligation");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("gen_sig")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("gen_sig");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("obligations")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("obligations");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("confirm_async_iterator_candidate")
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligation)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&gen_sig)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligations)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?obligation, ?gen_sig, ?obligations, "confirm_async_iterator_candidate");
1577
1578    let tcx = selcx.tcx();
1579    let iter_def_id = tcx.require_lang_item(LangItem::AsyncIterator, obligation.cause.span);
1580
1581    let (trait_ref, yield_ty) = super::util::async_iterator_trait_ref_and_outputs(
1582        tcx,
1583        iter_def_id,
1584        obligation.predicate.self_ty(),
1585        gen_sig,
1586    );
1587
1588    if true {
    {
        match (&tcx.associated_item(obligation.predicate.expect_projection_def_id()).name(),
                &sym::Item) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(
1589        tcx.associated_item(obligation.predicate.expect_projection_def_id()).name(),
1590        sym::Item
1591    );
1592
1593    let ty::Adt(_poll_adt, args) = *yield_ty.kind() else {
1594        ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller());bug!();
1595    };
1596    let ty::Adt(_option_adt, args) = *args.type_at(0).kind() else {
1597        ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller());bug!();
1598    };
1599    let item_ty = args.type_at(0);
1600
1601    let predicate = ty::ProjectionClause {
1602        projection_term: obligation.predicate.with_args(tcx, trait_ref.args),
1603        term: item_ty.into(),
1604    };
1605
1606    confirm_param_env_candidate(selcx, obligation, ty::Binder::dummy(predicate), false)
1607        .with_addl_obligations(nested)
1608        .with_addl_obligations(obligations)
1609}
1610
1611fn confirm_builtin_candidate<'cx, 'tcx>(
1612    selcx: &mut SelectionContext<'cx, 'tcx>,
1613    obligation: &ProjectionTermObligation<'tcx>,
1614    data: PredicateObligations<'tcx>,
1615) -> Progress<'tcx> {
1616    let tcx = selcx.tcx();
1617    let self_ty = obligation.predicate.self_ty();
1618    let item_def_id = obligation.predicate.expect_projection_def_id();
1619    let trait_def_id = tcx.parent(item_def_id);
1620    let args = tcx.mk_args(&[self_ty.into()]);
1621    let (term, obligations) = if tcx.is_lang_item(trait_def_id, LangItem::DiscriminantKind) {
1622        let discriminant_def_id =
1623            tcx.require_lang_item(LangItem::Discriminant, obligation.cause.span);
1624        {
    match (&discriminant_def_id, &item_def_id) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(discriminant_def_id, item_def_id);
1625
1626        (self_ty.discriminant_ty(tcx).into(), PredicateObligations::new())
1627    } else if tcx.is_lang_item(trait_def_id, LangItem::PointeeTrait) {
1628        let metadata_def_id = tcx.require_lang_item(LangItem::Metadata, obligation.cause.span);
1629        {
    match (&metadata_def_id, &item_def_id) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(metadata_def_id, item_def_id);
1630
1631        let mut obligations = PredicateObligations::new();
1632        let normalize = |ty: ty::Unnormalized<'tcx, Ty<'tcx>>| {
1633            normalize_with_depth_to(
1634                selcx,
1635                obligation.param_env,
1636                obligation.cause.clone(),
1637                obligation.recursion_depth + 1,
1638                ty,
1639                &mut obligations,
1640            )
1641        };
1642        let metadata_ty = self_ty.ptr_metadata_ty_or_tail(tcx, normalize).unwrap_or_else(|tail| {
1643            if tail == self_ty {
1644                // This is the "fallback impl" for type parameters, unnormalizable projections
1645                // and opaque types: If the `self_ty` is `Sized`, then the metadata is `()`.
1646                // FIXME(ptr_metadata): This impl overlaps with the other impls and shouldn't
1647                // exist. Instead, `Pointee<Metadata = ()>` should be a supertrait of `Sized`.
1648                let sized_predicate = ty::TraitRef::new(
1649                    tcx,
1650                    tcx.require_lang_item(LangItem::Sized, obligation.cause.span),
1651                    [self_ty],
1652                );
1653                obligations.push(obligation.with(tcx, sized_predicate));
1654                tcx.types.unit
1655            } else {
1656                // We know that `self_ty` has the same metadata as `tail`. This allows us
1657                // to prove predicates like `Wrapper<Tail>::Metadata == Tail::Metadata`.
1658                Ty::new_projection(tcx, ty::IsRigid::No, metadata_def_id, [tail])
1659            }
1660        });
1661        (metadata_ty.into(), obligations)
1662    } else if tcx.is_lang_item(trait_def_id, LangItem::Field) {
1663        let ty::Adt(def, args) = self_ty.kind() else {
1664            ::rustc_span::macros::bug_impl(None,
    format_args!("only field representing types can implement `Field`"),
    Location::caller())bug!("only field representing types can implement `Field`")
1665        };
1666        let Some(FieldInfo { base, ty, .. }) = def.field_representing_type_info(tcx, *args) else {
1667            ::rustc_span::macros::bug_impl(None,
    format_args!("only field representing types can implement `Field`"),
    Location::caller())bug!("only field representing types can implement `Field`")
1668        };
1669        if tcx.is_lang_item(item_def_id, LangItem::FieldBase) {
1670            (base.into(), PredicateObligations::new())
1671        } else if tcx.is_lang_item(item_def_id, LangItem::FieldType) {
1672            (ty.into(), PredicateObligations::new())
1673        } else {
1674            ::rustc_span::macros::bug_impl(None,
    format_args!("unexpected associated type {0:?} in `Field`",
        obligation.predicate), Location::caller());bug!("unexpected associated type {:?} in `Field`", obligation.predicate);
1675        }
1676    } else {
1677        ::rustc_span::macros::bug_impl(None,
    format_args!("unexpected builtin trait with associated type: {0:?}",
        obligation.predicate), Location::caller());bug!("unexpected builtin trait with associated type: {:?}", obligation.predicate);
1678    };
1679
1680    let predicate = ty::ProjectionClause {
1681        projection_term: ty::AliasTerm::new_from_args(
1682            tcx,
1683            ty::AliasTermKind::ProjectionTy { def_id: item_def_id },
1684            args,
1685        ),
1686        term,
1687    };
1688
1689    confirm_param_env_candidate(selcx, obligation, ty::Binder::dummy(predicate), false)
1690        .with_addl_obligations(obligations)
1691        .with_addl_obligations(data)
1692}
1693
1694fn confirm_fn_pointer_candidate<'cx, 'tcx>(
1695    selcx: &mut SelectionContext<'cx, 'tcx>,
1696    obligation: &ProjectionTermObligation<'tcx>,
1697    nested: PredicateObligations<'tcx>,
1698) -> Progress<'tcx> {
1699    let tcx = selcx.tcx();
1700    let fn_type = selcx.infcx.shallow_resolve(obligation.predicate.self_ty());
1701    let sig = fn_type.unnormalized_fn_sig(tcx);
1702    let Normalized { value: sig, obligations } = normalize_with_depth(
1703        selcx,
1704        obligation.param_env,
1705        obligation.cause.clone(),
1706        obligation.recursion_depth + 1,
1707        sig,
1708    );
1709
1710    confirm_callable_candidate(selcx, obligation, sig, util::TupleArgumentsFlag::Yes)
1711        .with_addl_obligations(nested)
1712        .with_addl_obligations(obligations)
1713}
1714
1715fn confirm_closure_candidate<'cx, 'tcx>(
1716    selcx: &mut SelectionContext<'cx, 'tcx>,
1717    obligation: &ProjectionTermObligation<'tcx>,
1718    nested: PredicateObligations<'tcx>,
1719) -> Progress<'tcx> {
1720    let tcx = selcx.tcx();
1721    let self_ty = selcx.infcx.shallow_resolve(obligation.predicate.self_ty());
1722    let closure_sig = match *self_ty.kind() {
1723        ty::Closure(_, args) => Unnormalized::new_wip(args.as_closure().sig()),
1724
1725        // Construct a "normal" `FnOnce` signature for coroutine-closure. This is
1726        // basically duplicated with the `AsyncFnOnce::CallOnce` confirmation, but
1727        // I didn't see a good way to unify those.
1728        ty::CoroutineClosure(def_id, args) => {
1729            let args = args.as_coroutine_closure();
1730            Unnormalized::new_wip(args.coroutine_closure_sig().map_bound(|sig| {
1731                let output_ty = coroutine_closure_output_coroutine(
1732                    tcx,
1733                    obligation,
1734                    ty::ClosureKind::FnOnce,
1735                    tcx.lifetimes.re_static,
1736                    def_id,
1737                    args,
1738                );
1739                tcx.mk_fn_sig([sig.tupled_inputs_ty], output_ty, sig.fn_sig_kind)
1740            }))
1741        }
1742
1743        _ => {
1744            {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("expected closure self type for closure candidate, found {0}",
                self_ty)));
};unreachable!("expected closure self type for closure candidate, found {self_ty}");
1745        }
1746    };
1747
1748    let Normalized { value: closure_sig, obligations } = normalize_with_depth(
1749        selcx,
1750        obligation.param_env,
1751        obligation.cause.clone(),
1752        obligation.recursion_depth + 1,
1753        closure_sig,
1754    );
1755
1756    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs:1756",
                        "rustc_trait_selection::traits::project",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs"),
                        ::tracing_core::__macro_support::Option::Some(1756u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::project"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("obligation")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("obligation");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("closure_sig")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("closure_sig");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("obligations")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("obligations");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("confirm_closure_candidate")
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligation)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_sig)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligations)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?obligation, ?closure_sig, ?obligations, "confirm_closure_candidate");
1757
1758    confirm_callable_candidate(selcx, obligation, closure_sig, util::TupleArgumentsFlag::No)
1759        .with_addl_obligations(nested)
1760        .with_addl_obligations(obligations)
1761}
1762
1763fn confirm_callable_candidate<'cx, 'tcx>(
1764    selcx: &mut SelectionContext<'cx, 'tcx>,
1765    obligation: &ProjectionTermObligation<'tcx>,
1766    fn_sig: ty::PolyFnSig<'tcx>,
1767    flag: util::TupleArgumentsFlag,
1768) -> Progress<'tcx> {
1769    let tcx = selcx.tcx();
1770
1771    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs:1771",
                        "rustc_trait_selection::traits::project",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs"),
                        ::tracing_core::__macro_support::Option::Some(1771u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::project"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("obligation")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("obligation");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("fn_sig")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("fn_sig");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("confirm_callable_candidate")
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligation)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_sig)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?obligation, ?fn_sig, "confirm_callable_candidate");
1772
1773    let fn_once_def_id = tcx.require_lang_item(LangItem::FnOnce, obligation.cause.span);
1774    let fn_once_output_def_id =
1775        tcx.require_lang_item(LangItem::FnOnceOutput, obligation.cause.span);
1776
1777    let predicate = super::util::closure_trait_ref_and_return_type(
1778        tcx,
1779        fn_once_def_id,
1780        obligation.predicate.self_ty(),
1781        fn_sig,
1782        flag,
1783    )
1784    .map_bound(|(trait_ref, ret_type)| ty::ProjectionClause {
1785        projection_term: ty::AliasTerm::new_from_args(
1786            tcx,
1787            ty::AliasTermKind::ProjectionTy { def_id: fn_once_output_def_id },
1788            trait_ref.args,
1789        ),
1790        term: ret_type.into(),
1791    });
1792
1793    confirm_param_env_candidate(selcx, obligation, predicate, true)
1794}
1795
1796fn confirm_async_closure_candidate<'cx, 'tcx>(
1797    selcx: &mut SelectionContext<'cx, 'tcx>,
1798    obligation: &ProjectionTermObligation<'tcx>,
1799    nested: PredicateObligations<'tcx>,
1800) -> Progress<'tcx> {
1801    let tcx = selcx.tcx();
1802    let self_ty = selcx.infcx.shallow_resolve(obligation.predicate.self_ty());
1803
1804    let goal_kind =
1805        tcx.async_fn_trait_kind_from_def_id(obligation.predicate.trait_def_id(tcx)).unwrap();
1806    let env_region = match goal_kind {
1807        ty::ClosureKind::Fn | ty::ClosureKind::FnMut => obligation.predicate.args.region_at(2),
1808        ty::ClosureKind::FnOnce => tcx.lifetimes.re_static,
1809    };
1810    let item_name = tcx.item_name(obligation.predicate.expect_projection_def_id());
1811
1812    let poly_cache_entry = match *self_ty.kind() {
1813        ty::CoroutineClosure(def_id, args) => {
1814            let args = args.as_coroutine_closure();
1815            let sig = args.coroutine_closure_sig().skip_binder();
1816
1817            let term = match item_name {
1818                sym::CallOnceFuture | sym::CallRefFuture => coroutine_closure_output_coroutine(
1819                    tcx, obligation, goal_kind, env_region, def_id, args,
1820                ),
1821                sym::Output => sig.return_ty,
1822                name => ::rustc_span::macros::bug_impl(None,
    format_args!("no such associated type: {0}", name), Location::caller())bug!("no such associated type: {name}"),
1823            };
1824            let projection_term = match item_name {
1825                sym::CallOnceFuture | sym::Output => ty::AliasTerm::new(
1826                    tcx,
1827                    obligation.predicate.kind,
1828                    [self_ty, sig.tupled_inputs_ty],
1829                ),
1830                sym::CallRefFuture => ty::AliasTerm::new(
1831                    tcx,
1832                    obligation.predicate.kind,
1833                    [ty::GenericArg::from(self_ty), sig.tupled_inputs_ty.into(), env_region.into()],
1834                ),
1835                name => ::rustc_span::macros::bug_impl(None,
    format_args!("no such associated type: {0}", name), Location::caller())bug!("no such associated type: {name}"),
1836            };
1837
1838            args.coroutine_closure_sig()
1839                .rebind(ty::ProjectionClause { projection_term, term: term.into() })
1840        }
1841        ty::FnDef(..) | ty::FnPtr(..) => {
1842            let bound_sig = self_ty.fn_sig(tcx);
1843            let sig = bound_sig.skip_binder();
1844
1845            let term = match item_name {
1846                sym::CallOnceFuture | sym::CallRefFuture => sig.output(),
1847                sym::Output => {
1848                    let future_output_def_id =
1849                        tcx.require_lang_item(LangItem::FutureOutput, obligation.cause.span);
1850                    Ty::new_projection(tcx, ty::IsRigid::No, future_output_def_id, [sig.output()])
1851                }
1852                name => ::rustc_span::macros::bug_impl(None,
    format_args!("no such associated type: {0}", name), Location::caller())bug!("no such associated type: {name}"),
1853            };
1854            let projection_term = match item_name {
1855                sym::CallOnceFuture | sym::Output => ty::AliasTerm::new(
1856                    tcx,
1857                    obligation.predicate.kind,
1858                    [self_ty, Ty::new_tup(tcx, sig.inputs())],
1859                ),
1860                sym::CallRefFuture => ty::AliasTerm::new(
1861                    tcx,
1862                    obligation.predicate.kind,
1863                    [
1864                        ty::GenericArg::from(self_ty),
1865                        Ty::new_tup(tcx, sig.inputs()).into(),
1866                        env_region.into(),
1867                    ],
1868                ),
1869                name => ::rustc_span::macros::bug_impl(None,
    format_args!("no such associated type: {0}", name), Location::caller())bug!("no such associated type: {name}"),
1870            };
1871
1872            bound_sig.rebind(ty::ProjectionClause { projection_term, term: term.into() })
1873        }
1874        ty::Closure(_, args) => {
1875            let args = args.as_closure();
1876            let bound_sig = args.sig();
1877            let sig = bound_sig.skip_binder();
1878
1879            let term = match item_name {
1880                sym::CallOnceFuture | sym::CallRefFuture => sig.output(),
1881                sym::Output => {
1882                    let future_output_def_id =
1883                        tcx.require_lang_item(LangItem::FutureOutput, obligation.cause.span);
1884                    Ty::new_projection(tcx, ty::IsRigid::No, future_output_def_id, [sig.output()])
1885                }
1886                name => ::rustc_span::macros::bug_impl(None,
    format_args!("no such associated type: {0}", name), Location::caller())bug!("no such associated type: {name}"),
1887            };
1888            let projection_term = match item_name {
1889                sym::CallOnceFuture | sym::Output => {
1890                    ty::AliasTerm::new(tcx, obligation.predicate.kind, [self_ty, sig.inputs()[0]])
1891                }
1892                sym::CallRefFuture => ty::AliasTerm::new(
1893                    tcx,
1894                    obligation.predicate.kind,
1895                    [ty::GenericArg::from(self_ty), sig.inputs()[0].into(), env_region.into()],
1896                ),
1897                name => ::rustc_span::macros::bug_impl(None,
    format_args!("no such associated type: {0}", name), Location::caller())bug!("no such associated type: {name}"),
1898            };
1899
1900            bound_sig.rebind(ty::ProjectionClause { projection_term, term: term.into() })
1901        }
1902        _ => ::rustc_span::macros::bug_impl(None,
    format_args!("expected callable type for AsyncFn candidate"),
    Location::caller())bug!("expected callable type for AsyncFn candidate"),
1903    };
1904
1905    confirm_param_env_candidate(selcx, obligation, poly_cache_entry, true)
1906        .with_addl_obligations(nested)
1907}
1908
1909/// Given a `CoroutineClosure(def_id, args)`, interpret it as a closure,
1910/// and return its output type for the given `goal_kind` and `env_region`.
1911fn coroutine_closure_output_coroutine<'tcx>(
1912    tcx: TyCtxt<'tcx>,
1913    obligation: &ProjectionTermObligation<'tcx>,
1914    goal_kind: ty::ClosureKind,
1915    env_region: ty::Region<'tcx>,
1916    def_id: DefId,
1917    args: ty::CoroutineClosureArgs<TyCtxt<'tcx>>,
1918) -> Ty<'tcx> {
1919    let kind_ty = args.kind_ty();
1920    let sig = args.coroutine_closure_sig().skip_binder();
1921
1922    // If we know the kind and upvars, use that directly.
1923    // Otherwise, defer to `AsyncFnKindHelper::Upvars` to delay
1924    // the projection, like the `AsyncFn*` traits do.
1925    if let Some(closure_kind) = kind_ty.to_opt_closure_kind()
1926        // Fall back to projection if upvars aren't constrained
1927        && !args.tupled_upvars_ty().is_ty_var()
1928    {
1929        if !closure_kind.extends(goal_kind) {
1930            ::rustc_span::macros::bug_impl(None,
    format_args!("we should not be confirming if the closure kind is not met"),
    Location::caller());bug!("we should not be confirming if the closure kind is not met");
1931        }
1932        sig.to_coroutine_given_kind_and_upvars(
1933            tcx,
1934            args.parent_args(),
1935            tcx.coroutine_for_closure(def_id),
1936            goal_kind,
1937            env_region,
1938            args.tupled_upvars_ty(),
1939            args.coroutine_captures_by_ref_ty(),
1940        )
1941    } else {
1942        let upvars_projection_def_id =
1943            tcx.require_lang_item(LangItem::AsyncFnKindUpvars, obligation.cause.span);
1944        // When we don't know the closure kind (and therefore also the closure's upvars,
1945        // which are computed at the same time), we must delay the computation of the
1946        // generator's upvars. We do this using the `AsyncFnKindHelper`, which as a trait
1947        // goal functions similarly to the old `ClosureKind` predicate, and ensures that
1948        // the goal kind <= the closure kind. As a projection `AsyncFnKindHelper::Upvars`
1949        // will project to the right upvars for the generator, appending the inputs and
1950        // coroutine upvars respecting the closure kind.
1951        // N.B. No need to register a `AsyncFnKindHelper` goal here, it's already in `nested`.
1952        let tupled_upvars_ty = Ty::new_projection(
1953            tcx,
1954            ty::IsRigid::No,
1955            upvars_projection_def_id,
1956            [
1957                ty::GenericArg::from(kind_ty),
1958                Ty::from_closure_kind(tcx, goal_kind).into(),
1959                env_region.into(),
1960                sig.tupled_inputs_ty.into(),
1961                args.tupled_upvars_ty().into(),
1962                args.coroutine_captures_by_ref_ty().into(),
1963            ],
1964        );
1965        sig.to_coroutine(
1966            tcx,
1967            args.parent_args(),
1968            Ty::from_closure_kind(tcx, goal_kind),
1969            tcx.coroutine_for_closure(def_id),
1970            tupled_upvars_ty,
1971        )
1972    }
1973}
1974
1975fn confirm_async_fn_kind_helper_candidate<'cx, 'tcx>(
1976    selcx: &mut SelectionContext<'cx, 'tcx>,
1977    obligation: &ProjectionTermObligation<'tcx>,
1978    nested: PredicateObligations<'tcx>,
1979) -> Progress<'tcx> {
1980    let [
1981        // We already checked that the goal_kind >= closure_kind
1982        _closure_kind_ty,
1983        goal_kind_ty,
1984        borrow_region,
1985        tupled_inputs_ty,
1986        tupled_upvars_ty,
1987        coroutine_captures_by_ref_ty,
1988    ] = *obligation.predicate.args.as_slice()
1989    else {
1990        ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller());bug!();
1991    };
1992
1993    let predicate = ty::ProjectionClause {
1994        projection_term: obligation.predicate.with_args(selcx.tcx(), obligation.predicate.args),
1995        term: ty::CoroutineClosureSignature::tupled_upvars_by_closure_kind(
1996            selcx.tcx(),
1997            goal_kind_ty.expect_ty().to_opt_closure_kind().unwrap(),
1998            tupled_inputs_ty.expect_ty(),
1999            tupled_upvars_ty.expect_ty(),
2000            coroutine_captures_by_ref_ty.expect_ty(),
2001            borrow_region.expect_region(),
2002        )
2003        .into(),
2004    };
2005
2006    confirm_param_env_candidate(selcx, obligation, ty::Binder::dummy(predicate), false)
2007        .with_addl_obligations(nested)
2008}
2009
2010// FIXME(mgca): While this supports constants, it is only used for types by default right now
2011fn confirm_param_env_candidate<'cx, 'tcx>(
2012    selcx: &mut SelectionContext<'cx, 'tcx>,
2013    obligation: &ProjectionTermObligation<'tcx>,
2014    poly_cache_entry: ty::PolyProjectionClause<'tcx>,
2015    potentially_unnormalized_candidate: bool,
2016) -> Progress<'tcx> {
2017    let infcx = selcx.infcx;
2018    let cause = &obligation.cause;
2019    let param_env = obligation.param_env;
2020
2021    let cache_entry = infcx.instantiate_binder_with_fresh_vars(
2022        cause.span,
2023        BoundRegionConversionTime::HigherRankedType,
2024        poly_cache_entry,
2025    );
2026
2027    let mut cache_projection = cache_entry.projection_term;
2028    let mut nested_obligations = PredicateObligations::new();
2029    let obligation_projection = obligation.predicate;
2030    let obligation_projection = normalize_with_depth_to(
2031        selcx,
2032        obligation.param_env,
2033        obligation.cause.clone(),
2034        obligation.recursion_depth + 1,
2035        ty::Unnormalized::new_wip(obligation_projection),
2036        &mut nested_obligations,
2037    );
2038    if potentially_unnormalized_candidate {
2039        cache_projection = normalize_with_depth_to(
2040            selcx,
2041            obligation.param_env,
2042            obligation.cause.clone(),
2043            obligation.recursion_depth + 1,
2044            ty::Unnormalized::new_wip(cache_projection),
2045            &mut nested_obligations,
2046        );
2047    }
2048
2049    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs:2049",
                        "rustc_trait_selection::traits::project",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs"),
                        ::tracing_core::__macro_support::Option::Some(2049u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::project"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("cache_projection")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("cache_projection");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("obligation_projection")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("obligation_projection");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cache_projection)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligation_projection)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?cache_projection, ?obligation_projection);
2050
2051    match infcx.eq_raw(
2052        cause,
2053        param_env,
2054        DefineOpaqueTypes::Yes,
2055        cache_projection,
2056        obligation_projection,
2057    ) {
2058        Ok(InferOk { value: _, obligations }) => {
2059            nested_obligations.extend(obligations);
2060            assoc_term_own_obligations(selcx, obligation, &mut nested_obligations);
2061            Progress {
2062                term: ty::Unnormalized::new(cache_entry.term),
2063                obligations: nested_obligations,
2064            }
2065        }
2066        Err(e) => {
2067            let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Failed to unify obligation `{0:?}` with poly_projection `{1:?}`: {2:?}",
                obligation, poly_cache_entry, e))
    })format!(
2068                "Failed to unify obligation `{obligation:?}` with poly_projection `{poly_cache_entry:?}`: {e:?}",
2069            );
2070            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs:2070",
                        "rustc_trait_selection::traits::project",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs"),
                        ::tracing_core::__macro_support::Option::Some(2070u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::project"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("confirm_param_env_candidate: {0}",
                                                    msg) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("confirm_param_env_candidate: {}", msg);
2071            let err = Ty::new_error_with_message(infcx.tcx, obligation.cause.span, msg);
2072            Progress {
2073                term: ty::Unnormalized::dummy(err.into()),
2074                obligations: PredicateObligations::new(),
2075            }
2076        }
2077    }
2078}
2079
2080// FIXME(mgca): While this supports constants, it is only used for types by default right now
2081fn confirm_impl_candidate<'cx, 'tcx>(
2082    selcx: &mut SelectionContext<'cx, 'tcx>,
2083    obligation: &ProjectionTermObligation<'tcx>,
2084    impl_impl_source: ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>>,
2085) -> Result<Projected<'tcx>, ProjectionError<'tcx>> {
2086    let tcx = selcx.tcx();
2087
2088    let ImplSourceUserDefinedData { impl_def_id, args, mut nested } = impl_impl_source;
2089
2090    let assoc_item_id = obligation.predicate.expect_projection_def_id();
2091    let trait_def_id = tcx.impl_trait_id(impl_def_id);
2092
2093    let param_env = obligation.param_env;
2094    let assoc_term = match specialization_graph::assoc_def(tcx, impl_def_id, assoc_item_id) {
2095        Ok(assoc_term) => assoc_term,
2096        Err(guar) => {
2097            return Ok(Projected::Progress(Progress::error_for_term(
2098                tcx,
2099                obligation.predicate,
2100                guar,
2101            )));
2102        }
2103    };
2104
2105    // This means that the impl is missing a definition for the
2106    // associated type. This is either because the associate item
2107    // has impossible-to-satisfy clauses (since those were
2108    // allowed in <https://github.com/rust-lang/rust/pull/135480>),
2109    // or because the impl is literally missing the definition.
2110    if !assoc_term.item.defaultness(tcx).has_value() {
2111        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs:2111",
                        "rustc_trait_selection::traits::project",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/project.rs"),
                        ::tracing_core::__macro_support::Option::Some(2111u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::project"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("confirm_impl_candidate: no associated type {0:?} for {1:?}",
                                                    assoc_term.item.name(), obligation.predicate) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
2112            "confirm_impl_candidate: no associated type {:?} for {:?}",
2113            assoc_term.item.name(),
2114            obligation.predicate
2115        );
2116        if tcx.impl_self_is_guaranteed_unsized(impl_def_id) {
2117            // We treat this projection as rigid here, which is represented via
2118            // `Projected::NoProgress`. This will ensure that the projection is
2119            // checked for well-formedness, and it's either satisfied by a trivial
2120            // where clause in its env or it results in an error.
2121            return Ok(Projected::NoProgress(obligation.predicate.to_term(tcx, ty::IsRigid::No)));
2122        } else {
2123            return Ok(Projected::Progress(Progress {
2124                term: ty::Unnormalized::dummy(if obligation.predicate.kind.is_type() {
2125                    Ty::new_misc_error(tcx).into()
2126                } else {
2127                    ty::Const::new_misc_error(tcx).into()
2128                }),
2129                obligations: nested,
2130            }));
2131        }
2132    }
2133
2134    // If we're trying to normalize `<Vec<u32> as X>::A<S>` using
2135    //`impl<T> X for Vec<T> { type A<Y> = Box<Y>; }`, then:
2136    //
2137    // * `obligation.predicate.args` is `[Vec<u32>, S]`
2138    // * `args` is `[u32]`
2139    // * `args` ends up as `[u32, S]`
2140    let args = obligation.predicate.args.rebase_onto(tcx, trait_def_id, args);
2141    let args = translate_args(selcx.infcx, param_env, impl_def_id, args, assoc_term.defining_node);
2142
2143    let term_kind = if obligation.predicate.kind.is_type() {
2144        ty::AliasTermKind::ProjectionTy { def_id: assoc_term.item.def_id }
2145    } else {
2146        ty::AliasTermKind::ProjectionConst { def_id: assoc_term.item.def_id }
2147    };
2148
2149    let progress = if !tcx.check_alias_term_args_compatible(term_kind, args) {
2150        let msg = "impl item and trait item have different parameters";
2151        let span = obligation.cause.span;
2152        let err = if obligation.predicate.kind.is_type() {
2153            Ty::new_error_with_message(tcx, span, msg).into()
2154        } else {
2155            ty::Const::new_error_with_message(tcx, span, msg).into()
2156        };
2157        Progress { term: ty::Unnormalized::dummy(err), obligations: nested }
2158    } else {
2159        let term = if obligation.predicate.kind.is_type() {
2160            tcx.type_of(assoc_term.item.def_id).map_bound(|ty| ty.into())
2161        } else {
2162            const_of_item_or_delayed_bug(tcx, assoc_term.item.def_id).map_bound(|ct| ct.into())
2163        };
2164
2165        assoc_term_own_obligations(selcx, obligation, &mut nested);
2166        let instantiated_term = term.instantiate(tcx, args);
2167        let term_for_obligation = instantiated_term.skip_norm_wip();
2168        push_const_arg_has_type_obligation(
2169            tcx,
2170            &mut nested,
2171            &obligation.cause,
2172            obligation.recursion_depth + 1,
2173            obligation.param_env,
2174            term_for_obligation,
2175            assoc_term.item.def_id,
2176            args,
2177        );
2178        Progress { term: instantiated_term, obligations: nested }
2179    };
2180    Ok(Projected::Progress(progress))
2181}
2182
2183// Get obligations corresponding to the predicates from the where-clause of the
2184// associated type itself.
2185//
2186// This is necessary for soundness until we properly handle implied bounds on binders.
2187// see tests/ui/generic-associated-types/must-prove-where-clauses-on-norm.rs.
2188// FIXME(mgca): While this supports constants, it is only used for types by default right now
2189fn assoc_term_own_obligations<'cx, 'tcx>(
2190    selcx: &mut SelectionContext<'cx, 'tcx>,
2191    obligation: &ProjectionTermObligation<'tcx>,
2192    nested: &mut PredicateObligations<'tcx>,
2193) {
2194    let tcx = selcx.tcx();
2195    let def_id = obligation.predicate.expect_projection_def_id();
2196    let clauses = tcx.clauses_of(def_id).instantiate_own(tcx, obligation.predicate.args);
2197    for (clause, span) in clauses {
2198        let normalized = normalize_with_depth_to(
2199            selcx,
2200            obligation.param_env,
2201            obligation.cause.clone(),
2202            obligation.recursion_depth + 1,
2203            clause,
2204            nested,
2205        );
2206
2207        let nested_cause = if #[allow(non_exhaustive_omitted_patterns)] match obligation.cause.code() {
    ObligationCauseCode::CompareImplItem { .. } |
        ObligationCauseCode::CheckAssociatedTypeBounds { .. } |
        ObligationCauseCode::AscribeUserTypeProvePredicate(..) => true,
    _ => false,
}matches!(
2208            obligation.cause.code(),
2209            ObligationCauseCode::CompareImplItem { .. }
2210                | ObligationCauseCode::CheckAssociatedTypeBounds { .. }
2211                | ObligationCauseCode::AscribeUserTypeProvePredicate(..)
2212        ) {
2213            obligation.cause.clone()
2214        } else {
2215            ObligationCause::new(
2216                obligation.cause.span,
2217                obligation.cause.body_def_id,
2218                ObligationCauseCode::WhereClause(def_id, span),
2219            )
2220        };
2221        nested.push(Obligation::with_depth(
2222            tcx,
2223            nested_cause,
2224            obligation.recursion_depth + 1,
2225            obligation.param_env,
2226            normalized,
2227        ));
2228    }
2229}
2230
2231pub(crate) trait ProjectionCacheKeyExt<'cx, 'tcx>: Sized {
2232    fn from_poly_projection_obligation(
2233        selcx: &mut SelectionContext<'cx, 'tcx>,
2234        obligation: &PolyProjectionObligation<'tcx>,
2235    ) -> Option<Self>;
2236}
2237
2238impl<'cx, 'tcx> ProjectionCacheKeyExt<'cx, 'tcx> for ProjectionCacheKey<'tcx> {
2239    fn from_poly_projection_obligation(
2240        selcx: &mut SelectionContext<'cx, 'tcx>,
2241        obligation: &PolyProjectionObligation<'tcx>,
2242    ) -> Option<Self> {
2243        let infcx = selcx.infcx;
2244        // We don't do cross-snapshot caching of obligations with escaping regions,
2245        // so there's no cache key to use
2246        obligation.predicate.no_bound_vars().map(|predicate| {
2247            ProjectionCacheKey::new(
2248                // We don't attempt to match up with a specific type-variable state
2249                // from a specific call to `opt_normalize_projection_type` - if
2250                // there's no precise match, the original cache entry is "stranded"
2251                // anyway.
2252                infcx.deeply_resolve_ignoring_regions(predicate.projection_term),
2253                obligation.param_env,
2254            )
2255        })
2256    }
2257}