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_data_structures::sso::SsoHashSet;
6use rustc_data_structures::stack::ensure_sufficient_stack;
7use rustc_errors::ErrorGuaranteed;
8use rustc_hir::lang_items::LangItem;
9use rustc_infer::infer::DefineOpaqueTypes;
10use rustc_infer::infer::resolve::OpportunisticRegionResolver;
11use rustc_infer::traits::{ObligationCauseCode, PredicateObligations};
12use rustc_middle::traits::select::OverflowError;
13use rustc_middle::traits::{BuiltinImplSource, ImplSource, ImplSourceUserDefinedData};
14use rustc_middle::ty::fast_reject::DeepRejectCtxt;
15use rustc_middle::ty::{
16    self, FieldInfo, Term, Ty, TyCtxt, TypeFoldable, TypeVisitableExt, TypingMode, Upcast,
17};
18use rustc_middle::{bug, span_bug};
19use rustc_span::sym;
20use tracing::{debug, instrument};
21
22use super::{
23    MismatchedProjectionTypes, Normalized, NormalizedTerm, Obligation, ObligationCause,
24    PredicateObligation, ProjectionCacheEntry, ProjectionCacheKey, Selection, SelectionContext,
25    SelectionError, specialization_graph, translate_args, util,
26};
27use crate::errors::InherentProjectionNormalizationOverflow;
28use crate::infer::{BoundRegionConversionTime, InferOk};
29use crate::traits::normalize::{normalize_with_depth, normalize_with_depth_to};
30use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
31use crate::traits::select::ProjectionMatchesProjection;
32
33pub type PolyProjectionObligation<'tcx> = Obligation<'tcx, ty::PolyProjectionPredicate<'tcx>>;
34
35pub type ProjectionObligation<'tcx> = Obligation<'tcx, ty::ProjectionPredicate<'tcx>>;
36
37pub type ProjectionTermObligation<'tcx> = Obligation<'tcx, ty::AliasTerm<'tcx>>;
38
39pub(super) struct InProgress;
40
41/// When attempting to resolve `<T as TraitRef>::Name` ...
42#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ProjectionError<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            ProjectionError::TooManyCandidates =>
                ::core::fmt::Formatter::write_str(f, "TooManyCandidates"),
            ProjectionError::TraitSelectionError(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "TraitSelectionError", &__self_0),
        }
    }
}Debug)]
43pub enum ProjectionError<'tcx> {
44    /// ...we found multiple sources of information and couldn't resolve the ambiguity.
45    TooManyCandidates,
46
47    /// ...an error occurred matching `T : TraitRef`
48    TraitSelectionError(SelectionError<'tcx>),
49}
50
51#[derive(#[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for ProjectionCandidate<'tcx> {
    #[inline]
    fn eq(&self, other: &ProjectionCandidate<'tcx>) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (ProjectionCandidate::ParamEnv(__self_0),
                    ProjectionCandidate::ParamEnv(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (ProjectionCandidate::TraitDef(__self_0),
                    ProjectionCandidate::TraitDef(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (ProjectionCandidate::Object(__self_0),
                    ProjectionCandidate::Object(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (ProjectionCandidate::Select(__self_0),
                    ProjectionCandidate::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::PolyProjectionPredicate<'tcx>>;
        let _:
                ::core::cmp::AssertParamIsEq<ty::PolyProjectionPredicate<'tcx>>;
        let _:
                ::core::cmp::AssertParamIsEq<ty::PolyProjectionPredicate<'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 {
            ProjectionCandidate::ParamEnv(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ParamEnv", &__self_0),
            ProjectionCandidate::TraitDef(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "TraitDef", &__self_0),
            ProjectionCandidate::Object(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Object",
                    &__self_0),
            ProjectionCandidate::Select(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Select",
                    &__self_0),
        }
    }
}Debug)]
52enum ProjectionCandidate<'tcx> {
53    /// From a where-clause in the env or object type
54    ParamEnv(ty::PolyProjectionPredicate<'tcx>),
55
56    /// From the definition of `Trait` when you have something like
57    /// `<<A as Trait>::B as Trait2>::C`.
58    TraitDef(ty::PolyProjectionPredicate<'tcx>),
59
60    /// Bounds specified on an object type
61    Object(ty::PolyProjectionPredicate<'tcx>),
62
63    /// From an "impl" (or a "pseudo-impl" returned by select)
64    Select(Selection<'tcx>),
65}
66
67enum ProjectionCandidateSet<'tcx> {
68    None,
69    Single(ProjectionCandidate<'tcx>),
70    Ambiguous,
71    Error(SelectionError<'tcx>),
72}
73
74impl<'tcx> ProjectionCandidateSet<'tcx> {
75    fn mark_ambiguous(&mut self) {
76        *self = ProjectionCandidateSet::Ambiguous;
77    }
78
79    fn mark_error(&mut self, err: SelectionError<'tcx>) {
80        *self = ProjectionCandidateSet::Error(err);
81    }
82
83    // Returns true if the push was successful, or false if the candidate
84    // was discarded -- this could be because of ambiguity, or because
85    // a higher-priority candidate is already there.
86    fn push_candidate(&mut self, candidate: ProjectionCandidate<'tcx>) -> bool {
87        // This wacky variable is just used to try and
88        // make code readable and avoid confusing paths.
89        // It is assigned a "value" of `()` only on those
90        // paths in which we wish to convert `*self` to
91        // ambiguous (and return false, because the candidate
92        // was not used). On other paths, it is not assigned,
93        // and hence if those paths *could* reach the code that
94        // comes after the match, this fn would not compile.
95        let convert_to_ambiguous;
96
97        match self {
98            ProjectionCandidateSet::None => {
99                *self = ProjectionCandidateSet::Single(candidate);
100                return true;
101            }
102
103            ProjectionCandidateSet::Single(current) => {
104                // Duplicates can happen inside ParamEnv. In the case, we
105                // perform a lazy deduplication.
106                if current == &candidate {
107                    return false;
108                }
109
110                // Prefer where-clauses. As in select, if there are multiple
111                // candidates, we prefer where-clause candidates over impls. This
112                // may seem a bit surprising, since impls are the source of
113                // "truth" in some sense, but in fact some of the impls that SEEM
114                // applicable are not, because of nested obligations. Where
115                // clauses are the safer choice. See the comment on
116                // `select::SelectionCandidate` and #21974 for more details.
117                match (current, candidate) {
118                    (ProjectionCandidate::ParamEnv(..), ProjectionCandidate::ParamEnv(..)) => {
119                        convert_to_ambiguous = ()
120                    }
121                    (ProjectionCandidate::ParamEnv(..), _) => return false,
122                    (_, ProjectionCandidate::ParamEnv(..)) => ::rustc_middle::util::bug::bug_fmt(format_args!("should never prefer non-param-env candidates over param-env candidates"))bug!(
123                        "should never prefer non-param-env candidates over param-env candidates"
124                    ),
125                    (_, _) => convert_to_ambiguous = (),
126                }
127            }
128
129            ProjectionCandidateSet::Ambiguous | ProjectionCandidateSet::Error(..) => {
130                return false;
131            }
132        }
133
134        // We only ever get here when we moved from a single candidate
135        // to ambiguous.
136        let () = convert_to_ambiguous;
137        *self = ProjectionCandidateSet::Ambiguous;
138        false
139    }
140}
141
142/// States returned from `poly_project_and_unify_type`. Takes the place
143/// of the old return type, which was:
144/// ```ignore (not-rust)
145/// Result<
146///     Result<Option<PredicateObligations<'tcx>>, InProgress>,
147///     MismatchedProjectionTypes<'tcx>,
148/// >
149/// ```
150pub(super) enum ProjectAndUnifyResult<'tcx> {
151    /// The projection bound holds subject to the given obligations. If the
152    /// projection cannot be normalized because the required trait bound does
153    /// not hold, this is returned, with `obligations` being a predicate that
154    /// cannot be proven.
155    Holds(PredicateObligations<'tcx>),
156    /// The projection cannot be normalized due to ambiguity. Resolving some
157    /// inference variables in the projection may fix this.
158    FailedNormalization,
159    /// The project cannot be normalized because `poly_project_and_unify_type`
160    /// is called recursively while normalizing the same projection.
161    Recursive,
162    // the projection can be normalized, but is not equal to the expected type.
163    // Returns the type error that arose from the mismatch.
164    MismatchedProjectionTypes(MismatchedProjectionTypes<'tcx>),
165}
166
167/// Evaluates constraints of the form:
168/// ```ignore (not-rust)
169/// for<...> <T as Trait>::U == V
170/// ```
171/// If successful, this may result in additional obligations. Also returns
172/// the projection cache key used to track these additional obligations.
173// FIXME(mgca): While this supports constants, it is only used for types by default right now
174#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("poly_project_and_unify_term",
                                    "rustc_trait_selection::traits::project",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/project.rs"),
                                    ::tracing_core::__macro_support::Option::Some(174u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::project"),
                                    ::tracing_core::field::FieldSet::new(&["obligation"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligation)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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