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