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