Skip to main content

rustc_next_trait_solver/solve/assembly/
structural_traits.rs

1//! Code which is used by built-in goals that match "structurally", such a auto
2//! traits, `Copy`/`Clone`.
3
4use derive_where::derive_where;
5use rustc_type_ir::data_structures::HashMap;
6use rustc_type_ir::inherent::*;
7use rustc_type_ir::lang_items::{SolverProjectionLangItem, SolverTraitLangItem};
8use rustc_type_ir::solve::SizedTraitKind;
9use rustc_type_ir::solve::inspect::ProbeKind;
10use rustc_type_ir::{
11    self as ty, FallibleTypeFolder, Interner, Movability, Mutability, Region, TypeFoldable,
12    TypeSuperFoldable, Unnormalized, Upcast as _, elaborate,
13};
14use rustc_type_ir_macros::{TypeFoldable_Generic, TypeVisitable_Generic};
15use tracing::instrument;
16
17use crate::delegate::SolverDelegate;
18use crate::solve::{
19    AdtDestructorKind, EvalCtxt, Goal, NoSolution, NoSolutionOrRerunNonErased, RerunNonErased,
20};
21
22// Calculates the constituent types of a type for `auto trait` purposes.
23{}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
            ::tracing::Level::TRACE <=
                ::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("instantiate_constituent_tys_for_auto_trait",
                                "rustc_next_trait_solver::solve::assembly::structural_traits",
                                ::tracing::Level::TRACE,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs"),
                                ::tracing_core::__macro_support::Option::Some(23u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly::structural_traits"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("ty")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("ty");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::TRACE <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::TRACE <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[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<ty::Binder<I, Vec<I::Ty>>, NoSolution> = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        let cx = ecx.cx();
                        match ty.kind() {
                            ty::Uint(_) | ty::Int(_) | ty::Bool | ty::Float(_) |
                                ty::FnDef(..) | ty::FnPtr(..) | ty::Error(_) | ty::Never |
                                ty::Char => Ok(ty::Binder::dummy(::alloc::vec::Vec::new())),
                            ty::Foreign(..) =>
                                Ok(ty::Binder::dummy(::alloc::vec::Vec::new())),
                            ty::Str =>
                                Ok(ty::Binder::dummy(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                                                [Ty::new_slice(cx, Ty::new_u8(cx))])))),
                            ty::Dynamic(..) | ty::Param(..) |
                                ty::Alias(ty::IsRigid::Yes, ty::AliasTy {
                                kind: ty::Projection { .. } | ty::Inherent { .. } |
                                    ty::Free { .. }, .. }) | ty::Placeholder(..) |
                                ty::Alias(ty::IsRigid::No, _) | ty::Bound(..) | ty::Infer(_)
                                |
                                ty::Alias(ty::IsRigid::Yes, ty::AliasTy {
                                kind: ty::Opaque { .. }, .. }) => {
                                {
                                    ::core::panicking::panic_fmt(format_args!("unexpected type `{0:?}`",
                                            ty));
                                }
                            }
                            ty::RawPtr(element_ty, _) | ty::Ref(_, element_ty, _) => {
                                Ok(ty::Binder::dummy(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                                                [element_ty]))))
                            }
                            ty::Pat(element_ty, _) | ty::Array(element_ty, _) |
                                ty::Slice(element_ty) => {
                                Ok(ty::Binder::dummy(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                                                [element_ty]))))
                            }
                            ty::Tuple(tys) => { Ok(ty::Binder::dummy(tys.to_vec())) }
                            ty::Closure(_, args) =>
                                Ok(ty::Binder::dummy(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                                                [args.as_closure().tupled_upvars_ty()])))),
                            ty::CoroutineClosure(_, args) => {
                                Ok(ty::Binder::dummy(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                                                [args.as_coroutine_closure().tupled_upvars_ty()]))))
                            }
                            ty::Coroutine(def_id, args) =>
                                Ok(ty::Binder::dummy(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                                                [args.as_coroutine().tupled_upvars_ty(),
                                                        Ty::new_coroutine_witness_for_coroutine(ecx.cx(), def_id,
                                                            args)])))),
                            ty::CoroutineWitness(def_id, args) =>
                                Ok(ecx.cx().coroutine_hidden_types(def_id).instantiate(cx,
                                                args).skip_norm_wip().map_bound(|bound|
                                            bound.types.to_vec())),
                            ty::UnsafeBinder(bound_ty) =>
                                Ok(bound_ty.map_bound(|ty|
                                            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                                                    [ty])))),
                            ty::Adt(def, args) if def.is_phantom_data() =>
                                Ok(ty::Binder::dummy(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                                                [args.type_at(0)])))),
                            ty::Adt(def, args) =>
                                Ok(ty::Binder::dummy(def.all_field_tys(cx).iter_instantiated(cx,
                                                    args).map(Unnormalized::skip_norm_wip).collect())),
                            ty::View(..) =>
                                ::core::panicking::unimplemented_default_msg(),
                        }
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs:23",
                        "rustc_next_trait_solver::solve::assembly::structural_traits",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs"),
                        ::tracing_core::__macro_support::Option::Some(23u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly::structural_traits"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "trace", skip(ecx), ret)]
24pub(in crate::solve) fn instantiate_constituent_tys_for_auto_trait<D, I>(
25    ecx: &EvalCtxt<'_, D>,
26    ty: I::Ty,
27) -> Result<ty::Binder<I, Vec<I::Ty>>, NoSolution>
28where
29    D: SolverDelegate<Interner = I>,
30    I: Interner,
31{
32    let cx = ecx.cx();
33    match ty.kind() {
34        ty::Uint(_)
35        | ty::Int(_)
36        | ty::Bool
37        | ty::Float(_)
38        | ty::FnDef(..)
39        | ty::FnPtr(..)
40        | ty::Error(_)
41        | ty::Never
42        | ty::Char => Ok(ty::Binder::dummy(vec![])),
43
44        // This branch is only for `experimental_default_bounds`.
45        // Other foreign types were rejected earlier in
46        // `disqualify_auto_trait_candidate_due_to_possible_impl`.
47        ty::Foreign(..) => Ok(ty::Binder::dummy(vec![])),
48
49        // Treat `str` like it's defined as `struct str([u8]);`
50        ty::Str => Ok(ty::Binder::dummy(vec![Ty::new_slice(cx, Ty::new_u8(cx))])),
51
52        ty::Dynamic(..)
53        | ty::Param(..)
54        | ty::Alias(
55            ty::IsRigid::Yes,
56            ty::AliasTy {
57                kind: ty::Projection { .. } | ty::Inherent { .. } | ty::Free { .. }, ..
58            },
59        )
60        | ty::Placeholder(..)
61        | ty::Alias(ty::IsRigid::No, _)
62        | ty::Bound(..)
63        | ty::Infer(_)
64        | ty::Alias(ty::IsRigid::Yes, ty::AliasTy { kind: ty::Opaque { .. }, .. }) => {
65            panic!("unexpected type `{ty:?}`")
66        }
67
68        ty::RawPtr(element_ty, _) | ty::Ref(_, element_ty, _) => {
69            Ok(ty::Binder::dummy(vec![element_ty]))
70        }
71
72        ty::Pat(element_ty, _) | ty::Array(element_ty, _) | ty::Slice(element_ty) => {
73            Ok(ty::Binder::dummy(vec![element_ty]))
74        }
75
76        ty::Tuple(tys) => {
77            // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
78            Ok(ty::Binder::dummy(tys.to_vec()))
79        }
80
81        ty::Closure(_, args) => Ok(ty::Binder::dummy(vec![args.as_closure().tupled_upvars_ty()])),
82
83        ty::CoroutineClosure(_, args) => {
84            Ok(ty::Binder::dummy(vec![args.as_coroutine_closure().tupled_upvars_ty()]))
85        }
86
87        ty::Coroutine(def_id, args) => Ok(ty::Binder::dummy(vec![
88            args.as_coroutine().tupled_upvars_ty(),
89            Ty::new_coroutine_witness_for_coroutine(ecx.cx(), def_id, args),
90        ])),
91
92        ty::CoroutineWitness(def_id, args) => Ok(ecx
93            .cx()
94            .coroutine_hidden_types(def_id)
95            .instantiate(cx, args)
96            .skip_norm_wip()
97            .map_bound(|bound| bound.types.to_vec())),
98
99        ty::UnsafeBinder(bound_ty) => Ok(bound_ty.map_bound(|ty| vec![ty])),
100
101        // For `PhantomData<T>`, we pass `T`.
102        ty::Adt(def, args) if def.is_phantom_data() => Ok(ty::Binder::dummy(vec![args.type_at(0)])),
103
104        ty::Adt(def, args) => Ok(ty::Binder::dummy(
105            def.all_field_tys(cx)
106                .iter_instantiated(cx, args)
107                .map(Unnormalized::skip_norm_wip)
108                .collect(),
109        )),
110
111        // FIXME(scrabsha)
112        ty::View(..) => unimplemented!(),
113    }
114}
115
116{}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
            ::tracing::Level::TRACE <=
                ::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("instantiate_constituent_tys_for_sizedness_trait",
                                "rustc_next_trait_solver::solve::assembly::structural_traits",
                                ::tracing::Level::TRACE,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs"),
                                ::tracing_core::__macro_support::Option::Some(116u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly::structural_traits"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("sizedness")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("sizedness");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("ty")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("ty");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::TRACE <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::TRACE <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sizedness)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[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<ty::Binder<I, Vec<I::Ty>>, NoSolution> = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        match ty.kind() {
                            ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) | ty::Uint(_) |
                                ty::Int(_) | ty::Bool | ty::Float(_) | ty::FnDef(..) |
                                ty::FnPtr(..) | ty::RawPtr(..) | ty::Char | ty::Ref(..) |
                                ty::Coroutine(..) | ty::CoroutineWitness(..) | ty::Array(..)
                                | ty::Pat(..) | ty::Closure(..) | ty::CoroutineClosure(..) |
                                ty::Never | ty::Error(_) =>
                                Ok(ty::Binder::dummy(::alloc::vec::Vec::new())),
                            ty::Str | ty::Slice(_) | ty::Dynamic(..) =>
                                match sizedness {
                                    SizedTraitKind::Sized => Err(NoSolution),
                                    SizedTraitKind::MetaSized =>
                                        Ok(ty::Binder::dummy(::alloc::vec::Vec::new())),
                                },
                            ty::Foreign(..) => Err(NoSolution),
                            ty::Alias(..) | ty::Param(_) | ty::Placeholder(..) =>
                                Err(NoSolution),
                            ty::Bound(..) |
                                ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_)
                                | ty::FreshFloatTy(_)) => {
                                {
                                    ::core::panicking::panic_fmt(format_args!("unexpected type `{0:?}`",
                                            ty));
                                }
                            }
                            ty::UnsafeBinder(bound_ty) =>
                                Ok(bound_ty.map_bound(|ty|
                                            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                                                    [ty])))),
                            ty::Tuple(tys) =>
                                Ok(ty::Binder::dummy(tys.last().map_or_else(Vec::new,
                                            |ty|
                                                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                                                        [ty]))))),
                            ty::Adt(def, args) => {
                                if let Some(crit) =
                                        def.sizedness_constraint(ecx.cx(), sizedness) {
                                    Ok(ty::Binder::dummy(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                                                    [crit.instantiate(ecx.cx(), args).skip_norm_wip()]))))
                                } else { Ok(ty::Binder::dummy(::alloc::vec::Vec::new())) }
                            }
                            ty::View(..) =>
                                ::core::panicking::unimplemented_default_msg(),
                        }
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs:116",
                        "rustc_next_trait_solver::solve::assembly::structural_traits",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs"),
                        ::tracing_core::__macro_support::Option::Some(116u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly::structural_traits"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "trace", skip(ecx), ret)]
117pub(in crate::solve) fn instantiate_constituent_tys_for_sizedness_trait<D, I>(
118    ecx: &EvalCtxt<'_, D>,
119    sizedness: SizedTraitKind,
120    ty: I::Ty,
121) -> Result<ty::Binder<I, Vec<I::Ty>>, NoSolution>
122where
123    D: SolverDelegate<Interner = I>,
124    I: Interner,
125{
126    match ty.kind() {
127        // impl {Meta,}Sized for u*, i*, bool, f*, FnDef, FnPtr, *(const/mut) T, char
128        // impl {Meta,}Sized for &mut? T, [T; N], dyn* Trait, !, Coroutine, CoroutineWitness
129        // impl {Meta,}Sized for Closure, CoroutineClosure
130        ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
131        | ty::Uint(_)
132        | ty::Int(_)
133        | ty::Bool
134        | ty::Float(_)
135        | ty::FnDef(..)
136        | ty::FnPtr(..)
137        | ty::RawPtr(..)
138        | ty::Char
139        | ty::Ref(..)
140        | ty::Coroutine(..)
141        | ty::CoroutineWitness(..)
142        | ty::Array(..)
143        | ty::Pat(..)
144        | ty::Closure(..)
145        | ty::CoroutineClosure(..)
146        | ty::Never
147        | ty::Error(_) => Ok(ty::Binder::dummy(vec![])),
148
149        // impl {Meta,}Sized for str, [T], dyn Trait
150        ty::Str | ty::Slice(_) | ty::Dynamic(..) => match sizedness {
151            SizedTraitKind::Sized => Err(NoSolution),
152            SizedTraitKind::MetaSized => Ok(ty::Binder::dummy(vec![])),
153        },
154
155        // impl {} for extern type
156        ty::Foreign(..) => Err(NoSolution),
157
158        ty::Alias(..) | ty::Param(_) | ty::Placeholder(..) => Err(NoSolution),
159
160        ty::Bound(..)
161        | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
162            panic!("unexpected type `{ty:?}`")
163        }
164
165        ty::UnsafeBinder(bound_ty) => Ok(bound_ty.map_bound(|ty| vec![ty])),
166
167        // impl {Meta,}Sized for ()
168        // impl {Meta,}Sized for (T1, T2, .., Tn) where Tn: {Meta,}Sized if n >= 1
169        ty::Tuple(tys) => Ok(ty::Binder::dummy(tys.last().map_or_else(Vec::new, |ty| vec![ty]))),
170
171        // impl {Meta,}Sized for Adt<Args...>
172        //   where {meta,pointee,}sized_constraint(Adt)<Args...>: {Meta,}Sized
173        //
174        //   `{meta,pointee,}sized_constraint(Adt)` is the deepest struct trail that can be
175        //   determined by the definition of `Adt`, independent of the generic args.
176        //
177        // impl {Meta,}Sized for Adt<Args...>
178        //   if {meta,pointee,}sized_constraint(Adt) == None
179        //
180        //   As a performance optimization, `{meta,pointee,}sized_constraint(Adt)` can return `None`
181        //   if the ADTs definition implies that it is {meta,}sized by for all possible args.
182        //   In this case, the builtin impl will have no nested subgoals. This is a
183        //   "best effort" optimization and `{meta,pointee,}sized_constraint` may return `Some`,
184        //   even if the ADT is {meta,pointee,}sized for all possible args.
185        ty::Adt(def, args) => {
186            if let Some(crit) = def.sizedness_constraint(ecx.cx(), sizedness) {
187                Ok(ty::Binder::dummy(vec![crit.instantiate(ecx.cx(), args).skip_norm_wip()]))
188            } else {
189                Ok(ty::Binder::dummy(vec![]))
190            }
191        }
192
193        // FIXME(scrabsha)
194        ty::View(..) => unimplemented!(),
195    }
196}
197
198{}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
            ::tracing::Level::TRACE <=
                ::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("instantiate_constituent_tys_for_copy_clone_trait",
                                "rustc_next_trait_solver::solve::assembly::structural_traits",
                                ::tracing::Level::TRACE,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs"),
                                ::tracing_core::__macro_support::Option::Some(198u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly::structural_traits"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("ty")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("ty");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::TRACE <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::TRACE <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[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<ty::Binder<I, Vec<I::Ty>>, NoSolution> = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        match ty.kind() {
                            ty::FnDef(..) | ty::FnPtr(..) | ty::Error(_) =>
                                Ok(ty::Binder::dummy(::alloc::vec::Vec::new())),
                            ty::Uint(_) | ty::Int(_) |
                                ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) | ty::Bool |
                                ty::Float(_) | ty::Char | ty::RawPtr(..) | ty::Never |
                                ty::Ref(_, _, Mutability::Not) | ty::Array(..) =>
                                Err(NoSolution),
                            ty::Pat(ty, ..) =>
                                Ok(ty::Binder::dummy(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                                                [ty])))),
                            ty::Dynamic(..) | ty::Str | ty::Slice(_) | ty::Foreign(..) |
                                ty::Ref(_, _, Mutability::Mut) | ty::Adt(_, _) |
                                ty::Alias(ty::IsRigid::Yes, _) | ty::Param(_) |
                                ty::Placeholder(..) => Err(NoSolution),
                            ty::Tuple(tys) => Ok(ty::Binder::dummy(tys.to_vec())),
                            ty::Closure(_, args) =>
                                Ok(ty::Binder::dummy(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                                                [args.as_closure().tupled_upvars_ty()])))),
                            ty::CoroutineClosure(_, args) => {
                                Ok(ty::Binder::dummy(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                                                [args.as_coroutine_closure().tupled_upvars_ty()]))))
                            }
                            ty::Coroutine(def_id, args) =>
                                match ecx.cx().coroutine_movability(def_id) {
                                    Movability::Static => Err(NoSolution),
                                    Movability::Movable => {
                                        if ecx.cx().features().coroutine_clone() {
                                            Ok(ty::Binder::dummy(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                                                            [args.as_coroutine().tupled_upvars_ty(),
                                                                    Ty::new_coroutine_witness_for_coroutine(ecx.cx(), def_id,
                                                                        args)]))))
                                        } else { Err(NoSolution) }
                                    }
                                },
                            ty::UnsafeBinder(_) => Err(NoSolution),
                            ty::CoroutineWitness(def_id, args) =>
                                Ok(ecx.cx().coroutine_hidden_types(def_id).instantiate(ecx.cx(),
                                                args).skip_norm_wip().map_bound(|bound|
                                            bound.types.to_vec())),
                            ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_)
                                | ty::FreshFloatTy(_)) | ty::Alias(ty::IsRigid::No, _) |
                                ty::Bound(..) => {
                                {
                                    ::core::panicking::panic_fmt(format_args!("unexpected type `{0:?}`",
                                            ty));
                                }
                            }
                            ty::View(..) =>
                                ::core::panicking::unimplemented_default_msg(),
                        }
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs:198",
                        "rustc_next_trait_solver::solve::assembly::structural_traits",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs"),
                        ::tracing_core::__macro_support::Option::Some(198u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly::structural_traits"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "trace", skip(ecx), ret)]
199pub(in crate::solve) fn instantiate_constituent_tys_for_copy_clone_trait<D, I>(
200    ecx: &EvalCtxt<'_, D>,
201    ty: I::Ty,
202) -> Result<ty::Binder<I, Vec<I::Ty>>, NoSolution>
203where
204    D: SolverDelegate<Interner = I>,
205    I: Interner,
206{
207    match ty.kind() {
208        // impl Copy/Clone for FnDef, FnPtr
209        ty::FnDef(..) | ty::FnPtr(..) | ty::Error(_) => Ok(ty::Binder::dummy(vec![])),
210
211        // Implementations are provided in core
212        ty::Uint(_)
213        | ty::Int(_)
214        | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
215        | ty::Bool
216        | ty::Float(_)
217        | ty::Char
218        | ty::RawPtr(..)
219        | ty::Never
220        | ty::Ref(_, _, Mutability::Not)
221        | ty::Array(..) => Err(NoSolution),
222
223        // Cannot implement in core, as we can't be generic over patterns yet,
224        // so we'd have to list all patterns and type combinations.
225        ty::Pat(ty, ..) => Ok(ty::Binder::dummy(vec![ty])),
226
227        ty::Dynamic(..)
228        | ty::Str
229        | ty::Slice(_)
230        | ty::Foreign(..)
231        | ty::Ref(_, _, Mutability::Mut)
232        | ty::Adt(_, _)
233        | ty::Alias(ty::IsRigid::Yes, _)
234        | ty::Param(_)
235        | ty::Placeholder(..) => Err(NoSolution),
236
237        // impl Copy/Clone for (T1, T2, .., Tn) where T1: Copy/Clone, T2: Copy/Clone, .. Tn: Copy/Clone
238        ty::Tuple(tys) => Ok(ty::Binder::dummy(tys.to_vec())),
239
240        // impl Copy/Clone for Closure where Self::TupledUpvars: Copy/Clone
241        ty::Closure(_, args) => Ok(ty::Binder::dummy(vec![args.as_closure().tupled_upvars_ty()])),
242
243        // impl Copy/Clone for CoroutineClosure where Self::TupledUpvars: Copy/Clone
244        ty::CoroutineClosure(_, args) => {
245            Ok(ty::Binder::dummy(vec![args.as_coroutine_closure().tupled_upvars_ty()]))
246        }
247
248        // only when `coroutine_clone` is enabled and the coroutine is movable
249        // impl Copy/Clone for Coroutine where T: Copy/Clone forall T in (upvars, witnesses)
250        ty::Coroutine(def_id, args) => match ecx.cx().coroutine_movability(def_id) {
251            Movability::Static => Err(NoSolution),
252            Movability::Movable => {
253                if ecx.cx().features().coroutine_clone() {
254                    Ok(ty::Binder::dummy(vec![
255                        args.as_coroutine().tupled_upvars_ty(),
256                        Ty::new_coroutine_witness_for_coroutine(ecx.cx(), def_id, args),
257                    ]))
258                } else {
259                    Err(NoSolution)
260                }
261            }
262        },
263
264        ty::UnsafeBinder(_) => Err(NoSolution),
265
266        // impl Copy/Clone for CoroutineWitness where T: Copy/Clone forall T in coroutine_hidden_types
267        ty::CoroutineWitness(def_id, args) => Ok(ecx
268            .cx()
269            .coroutine_hidden_types(def_id)
270            .instantiate(ecx.cx(), args)
271            .skip_norm_wip()
272            .map_bound(|bound| bound.types.to_vec())),
273
274        ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_))
275        | ty::Alias(ty::IsRigid::No, _)
276        | ty::Bound(..) => {
277            panic!("unexpected type `{ty:?}`")
278        }
279
280        // FIXME(scrabsha)
281        ty::View(..) => unimplemented!(),
282    }
283}
284
285// Returns a binder of the tupled inputs types and output type from a builtin callable type.
286pub(in crate::solve) fn extract_tupled_inputs_and_output_from_callable<I: Interner>(
287    cx: I,
288    self_ty: I::Ty,
289    goal_kind: ty::ClosureKind,
290) -> Result<Option<ty::Binder<I, (I::Ty, I::Ty)>>, NoSolution> {
291    match self_ty.kind() {
292        // keep this in sync with assemble_fn_pointer_candidates until the old solver is removed.
293        ty::FnDef(def_id, args) => {
294            let sig = cx.fn_sig(def_id);
295            if sig.skip_binder().is_fn_trait_compatible() && !cx.has_target_features(def_id) {
296                Ok(Some(
297                    sig.instantiate(cx, args.no_bound_vars().unwrap())
298                        .skip_norm_wip()
299                        .map_bound(|sig| (Ty::new_tup(cx, sig.inputs().as_slice()), sig.output())),
300                ))
301            } else {
302                Err(NoSolution)
303            }
304        }
305        // keep this in sync with assemble_fn_pointer_candidates until the old solver is removed.
306        ty::FnPtr(sig_tys, hdr) => {
307            let sig = sig_tys.with(hdr);
308            if sig.is_fn_trait_compatible() {
309                Ok(Some(
310                    sig.map_bound(|sig| (Ty::new_tup(cx, sig.inputs().as_slice()), sig.output())),
311                ))
312            } else {
313                Err(NoSolution)
314            }
315        }
316        ty::Closure(_, args) => {
317            let closure_args = args.as_closure();
318            match closure_args.kind_ty().to_opt_closure_kind() {
319                // If the closure's kind doesn't extend the goal kind,
320                // then the closure doesn't implement the trait.
321                Some(closure_kind) => {
322                    if !closure_kind.extends(goal_kind) {
323                        return Err(NoSolution);
324                    }
325                }
326                // Closure kind is not yet determined, so we return ambiguity unless
327                // the expected kind is `FnOnce` as that is always implemented.
328                None => {
329                    if goal_kind != ty::ClosureKind::FnOnce {
330                        return Ok(None);
331                    }
332                }
333            }
334            Ok(Some(
335                closure_args.sig().map_bound(|sig| (sig.inputs().get(0).unwrap(), sig.output())),
336            ))
337        }
338
339        // Coroutine-closures don't implement `Fn` traits the normal way.
340        // Instead, they always implement `FnOnce`, but only implement
341        // `FnMut`/`Fn` if they capture no upvars, since those may borrow
342        // from the closure.
343        ty::CoroutineClosure(def_id, args) => {
344            let args = args.as_coroutine_closure();
345            let kind_ty = args.kind_ty();
346            let sig = args.coroutine_closure_sig().skip_binder();
347
348            let coroutine_ty = if let Some(kind) = kind_ty.to_opt_closure_kind()
349                && !args.tupled_upvars_ty().is_ty_var()
350            {
351                if !kind.extends(goal_kind) {
352                    return Err(NoSolution);
353                }
354
355                // A coroutine-closure implements `FnOnce` *always*, since it may
356                // always be called once. It additionally implements `Fn`/`FnMut`
357                // only if it has no upvars referencing the closure-env lifetime,
358                // and if the closure kind permits it.
359                if goal_kind != ty::ClosureKind::FnOnce && args.has_self_borrows() {
360                    return Err(NoSolution);
361                }
362
363                coroutine_closure_to_certain_coroutine(
364                    cx,
365                    goal_kind,
366                    // No captures by ref, so this doesn't matter.
367                    Region::new_static(cx),
368                    def_id,
369                    args,
370                    sig,
371                )
372            } else {
373                // Closure kind is not yet determined, so we return ambiguity unless
374                // the expected kind is `FnOnce` as that is always implemented.
375                if goal_kind != ty::ClosureKind::FnOnce {
376                    return Ok(None);
377                }
378
379                coroutine_closure_to_ambiguous_coroutine(
380                    cx,
381                    goal_kind, // No captures by ref, so this doesn't matter.
382                    Region::new_static(cx),
383                    def_id,
384                    args,
385                    sig,
386                )
387            };
388
389            Ok(Some(args.coroutine_closure_sig().rebind((sig.tupled_inputs_ty, coroutine_ty))))
390        }
391
392        ty::Bool
393        | ty::Char
394        | ty::Int(_)
395        | ty::Uint(_)
396        | ty::Float(_)
397        | ty::Adt(_, _)
398        | ty::Foreign(_)
399        | ty::Str
400        | ty::Array(_, _)
401        | ty::Slice(_)
402        | ty::RawPtr(_, _)
403        | ty::Ref(_, _, _)
404        | ty::Dynamic(_, _)
405        | ty::Coroutine(_, _)
406        | ty::CoroutineWitness(..)
407        | ty::Never
408        | ty::Tuple(_)
409        | ty::Pat(_, _)
410        | ty::UnsafeBinder(_)
411        | ty::Alias(ty::IsRigid::Yes, _)
412        | ty::Param(_)
413        | ty::Placeholder(..)
414        | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
415        | ty::Error(_) => Err(NoSolution),
416
417        ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_))
418        | ty::Alias(ty::IsRigid::No, _)
419        | ty::Bound(..) => {
420            {
    ::core::panicking::panic_fmt(format_args!("unexpected type `{0:?}`",
            self_ty));
}panic!("unexpected type `{self_ty:?}`")
421        }
422
423        // FIXME(scrabsha)
424        ty::View(..) => ::core::panicking::unimplemented_default_msg()unimplemented!(),
425    }
426}
427
428/// Relevant types for an async callable, including its inputs, output,
429/// and the return type you get from awaiting the output.
430#[automatically_derived]
impl<I: Interner> ::core::clone::Clone for AsyncCallableRelevantTypes<I> where
    I: Interner {
    #[inline]
    fn clone(&self) -> Self { *self }
}
#[automatically_derived]
impl<I: Interner> ::core::marker::Copy for AsyncCallableRelevantTypes<I> where
    I: Interner {
}
#[automatically_derived]
impl<I: Interner> ::core::fmt::Debug for AsyncCallableRelevantTypes<I> where
    I: Interner {
    fn fmt(&self, __f: &mut ::core::fmt::Formatter<'_>)
        -> ::core::fmt::Result {
        match self {
            AsyncCallableRelevantTypes {
                tupled_inputs_ty: ref __field_tupled_inputs_ty,
                output_coroutine_ty: ref __field_output_coroutine_ty,
                coroutine_return_ty: ref __field_coroutine_return_ty } => {
                let mut __builder =
                    ::core::fmt::Formatter::debug_struct(__f,
                        "AsyncCallableRelevantTypes");
                ::core::fmt::DebugStruct::field(&mut __builder,
                    "tupled_inputs_ty", __field_tupled_inputs_ty);
                ::core::fmt::DebugStruct::field(&mut __builder,
                    "output_coroutine_ty", __field_output_coroutine_ty);
                ::core::fmt::DebugStruct::field(&mut __builder,
                    "coroutine_return_ty", __field_coroutine_return_ty);
                ::core::fmt::DebugStruct::finish(&mut __builder)
            }
        }
    }
}#[derive_where(Clone, Copy, Debug; I: Interner)]
431#[derive(const _: () =
    {
        impl<I: Interner> ::rustc_type_ir::TypeVisitable<I> for
            AsyncCallableRelevantTypes<I> where I: Interner,
            I::Ty: ::rustc_type_ir::TypeVisitable<I> {
            fn visit_with<__V: ::rustc_type_ir::TypeVisitor<I>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    AsyncCallableRelevantTypes {
                        tupled_inputs_ty: ref __binding_0,
                        output_coroutine_ty: ref __binding_1,
                        coroutine_return_ty: ref __binding_2 } => {
                        {
                            match ::rustc_type_ir::VisitorResult::branch(::rustc_type_ir::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_type_ir::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_type_ir::VisitorResult::branch(::rustc_type_ir::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_type_ir::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_type_ir::VisitorResult::branch(::rustc_type_ir::TypeVisitable::visit_with(__binding_2,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_type_ir::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_type_ir::VisitorResult>::output()
            }
        }
    };TypeVisitable_Generic, const _: () =
    {
        impl<I: Interner> ::rustc_type_ir::TypeFoldable<I> for
            AsyncCallableRelevantTypes<I> where I: Interner,
            I::Ty: ::rustc_type_ir::TypeFoldable<I> {
            fn try_fold_with<__F: ::rustc_type_ir::FallibleTypeFolder<I>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        AsyncCallableRelevantTypes {
                            tupled_inputs_ty: __binding_0,
                            output_coroutine_ty: __binding_1,
                            coroutine_return_ty: __binding_2 } => {
                            AsyncCallableRelevantTypes {
                                tupled_inputs_ty: ::rustc_type_ir::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                output_coroutine_ty: ::rustc_type_ir::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?,
                                coroutine_return_ty: ::rustc_type_ir::TypeFoldable::try_fold_with(__binding_2,
                                        __folder)?,
                            }
                        }
                    })
            }
            fn fold_with<__F: ::rustc_type_ir::TypeFolder<I>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    AsyncCallableRelevantTypes {
                        tupled_inputs_ty: __binding_0,
                        output_coroutine_ty: __binding_1,
                        coroutine_return_ty: __binding_2 } => {
                        AsyncCallableRelevantTypes {
                            tupled_inputs_ty: ::rustc_type_ir::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            output_coroutine_ty: ::rustc_type_ir::TypeFoldable::fold_with(__binding_1,
                                __folder),
                            coroutine_return_ty: ::rustc_type_ir::TypeFoldable::fold_with(__binding_2,
                                __folder),
                        }
                    }
                }
            }
        }
    };TypeFoldable_Generic)]
432pub(in crate::solve) struct AsyncCallableRelevantTypes<I: Interner> {
433    pub tupled_inputs_ty: I::Ty,
434    /// Type returned by calling the closure
435    /// i.e. `f()`.
436    pub output_coroutine_ty: I::Ty,
437    /// Type returned by `await`ing the output
438    /// i.e. `f().await`.
439    pub coroutine_return_ty: I::Ty,
440}
441
442// Returns a binder of the tupled inputs types, output type, and coroutine type
443// from a builtin coroutine-closure type. If we don't yet know the closure kind of
444// the coroutine-closure, emit an additional trait predicate for `AsyncFnKindHelper`
445// which enforces the closure is actually callable with the given trait. When we
446// know the kind already, we can short-circuit this check.
447pub(in crate::solve) fn extract_tupled_inputs_and_output_from_async_callable<I: Interner>(
448    cx: I,
449    self_ty: I::Ty,
450    goal_kind: ty::ClosureKind,
451    env_region: Region<I>,
452) -> Result<(ty::Binder<I, AsyncCallableRelevantTypes<I>>, Vec<I::Predicate>), NoSolution> {
453    match self_ty.kind() {
454        ty::CoroutineClosure(def_id, args) => {
455            if !cx.coroutine_is_async(cx.coroutine_for_closure(def_id)) {
456                return Err(NoSolution);
457            }
458
459            let args = args.as_coroutine_closure();
460            let kind_ty = args.kind_ty();
461            let sig = args.coroutine_closure_sig().skip_binder();
462            let mut nested = ::alloc::vec::Vec::new()vec![];
463
464            let coroutine_ty = if let Some(kind) = kind_ty.to_opt_closure_kind()
465                && !args.tupled_upvars_ty().is_ty_var()
466            {
467                if !kind.extends(goal_kind) {
468                    return Err(NoSolution);
469                }
470
471                coroutine_closure_to_certain_coroutine(cx, goal_kind, env_region, def_id, args, sig)
472            } else {
473                // When we don't know the closure kind (and therefore also the closure's upvars,
474                // which are computed at the same time), we must delay the computation of the
475                // generator's upvars. We do this using the `AsyncFnKindHelper`, which as a trait
476                // goal functions similarly to the old `ClosureKind` predicate, and ensures that
477                // the goal kind <= the closure kind. As a projection `AsyncFnKindHelper::Upvars`
478                // will project to the right upvars for the generator, appending the inputs and
479                // coroutine upvars respecting the closure kind.
480                nested.push(
481                    ty::TraitRef::new(
482                        cx,
483                        cx.require_trait_lang_item(SolverTraitLangItem::AsyncFnKindHelper),
484                        [kind_ty, Ty::from_closure_kind(cx, goal_kind)],
485                    )
486                    .upcast(cx),
487                );
488
489                coroutine_closure_to_ambiguous_coroutine(
490                    cx, goal_kind, env_region, def_id, args, sig,
491                )
492            };
493
494            Ok((
495                args.coroutine_closure_sig().rebind(AsyncCallableRelevantTypes {
496                    tupled_inputs_ty: sig.tupled_inputs_ty,
497                    output_coroutine_ty: coroutine_ty,
498                    coroutine_return_ty: sig.return_ty,
499                }),
500                nested,
501            ))
502        }
503
504        ty::FnDef(def_id, _) => {
505            let sig = self_ty.fn_sig(cx);
506            if sig.is_fn_trait_compatible() && !cx.has_target_features(def_id) {
507                fn_item_to_async_callable(cx, sig)
508            } else {
509                Err(NoSolution)
510            }
511        }
512        ty::FnPtr(..) => {
513            let sig = self_ty.fn_sig(cx);
514            if sig.is_fn_trait_compatible() {
515                fn_item_to_async_callable(cx, sig)
516            } else {
517                Err(NoSolution)
518            }
519        }
520
521        ty::Closure(_, args) => {
522            let args = args.as_closure();
523            let bound_sig = args.sig();
524            let sig = bound_sig.skip_binder();
525            let future_trait_def_id = cx.require_trait_lang_item(SolverTraitLangItem::Future);
526            // `Closure`s only implement `AsyncFn*` when their return type
527            // implements `Future`.
528            let mut nested = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [bound_sig.rebind(ty::TraitRef::new(cx, future_trait_def_id,
                            [sig.output()])).upcast(cx)]))vec![
529                bound_sig
530                    .rebind(ty::TraitRef::new(cx, future_trait_def_id, [sig.output()]))
531                    .upcast(cx),
532            ];
533
534            // Additionally, we need to check that the closure kind
535            // is still compatible.
536            let kind_ty = args.kind_ty();
537            if let Some(closure_kind) = kind_ty.to_opt_closure_kind() {
538                if !closure_kind.extends(goal_kind) {
539                    return Err(NoSolution);
540                }
541            } else {
542                let async_fn_kind_trait_def_id =
543                    cx.require_trait_lang_item(SolverTraitLangItem::AsyncFnKindHelper);
544                // When we don't know the closure kind (and therefore also the closure's upvars,
545                // which are computed at the same time), we must delay the computation of the
546                // generator's upvars. We do this using the `AsyncFnKindHelper`, which as a trait
547                // goal functions similarly to the old `ClosureKind` predicate, and ensures that
548                // the goal kind <= the closure kind. As a projection `AsyncFnKindHelper::Upvars`
549                // will project to the right upvars for the generator, appending the inputs and
550                // coroutine upvars respecting the closure kind.
551                nested.push(
552                    ty::TraitRef::new(
553                        cx,
554                        async_fn_kind_trait_def_id,
555                        [kind_ty, Ty::from_closure_kind(cx, goal_kind)],
556                    )
557                    .upcast(cx),
558                );
559            }
560
561            let future_output_def_id =
562                cx.require_projection_lang_item(SolverProjectionLangItem::FutureOutput);
563            let future_output_ty =
564                Ty::new_projection(cx, ty::IsRigid::No, future_output_def_id, [sig.output()]);
565            Ok((
566                bound_sig.rebind(AsyncCallableRelevantTypes {
567                    tupled_inputs_ty: sig.inputs().get(0).unwrap(),
568                    output_coroutine_ty: sig.output(),
569                    coroutine_return_ty: future_output_ty,
570                }),
571                nested,
572            ))
573        }
574
575        ty::Bool
576        | ty::Char
577        | ty::Int(_)
578        | ty::Uint(_)
579        | ty::Float(_)
580        | ty::Adt(_, _)
581        | ty::Foreign(_)
582        | ty::Str
583        | ty::Array(_, _)
584        | ty::Pat(_, _)
585        | ty::Slice(_)
586        | ty::RawPtr(_, _)
587        | ty::Ref(_, _, _)
588        | ty::Dynamic(_, _)
589        | ty::Coroutine(_, _)
590        | ty::CoroutineWitness(..)
591        | ty::Never
592        | ty::UnsafeBinder(_)
593        | ty::Tuple(_)
594        | ty::Alias(ty::IsRigid::Yes, _)
595        | ty::Param(_)
596        | ty::Placeholder(..)
597        | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
598        | ty::Error(_) => Err(NoSolution),
599
600        ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_))
601        | ty::Alias(ty::IsRigid::No, _)
602        | ty::Bound(..) => {
603            {
    ::core::panicking::panic_fmt(format_args!("unexpected type `{0:?}`",
            self_ty));
}panic!("unexpected type `{self_ty:?}`")
604        }
605
606        // FIXME(scrabsha)
607        ty::View(..) => ::core::panicking::unimplemented_default_msg()unimplemented!(),
608    }
609}
610
611fn fn_item_to_async_callable<I: Interner>(
612    cx: I,
613    bound_sig: ty::Binder<I, ty::FnSig<I>>,
614) -> Result<(ty::Binder<I, AsyncCallableRelevantTypes<I>>, Vec<I::Predicate>), NoSolution> {
615    let sig = bound_sig.skip_binder();
616    let future_trait_def_id = cx.require_trait_lang_item(SolverTraitLangItem::Future);
617    // `FnDef` and `FnPtr` only implement `AsyncFn*` when their
618    // return type implements `Future`.
619    let nested = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [bound_sig.rebind(ty::TraitRef::new(cx, future_trait_def_id,
                            [sig.output()])).upcast(cx)]))vec![
620        bound_sig.rebind(ty::TraitRef::new(cx, future_trait_def_id, [sig.output()])).upcast(cx),
621    ];
622    let future_output_def_id =
623        cx.require_projection_lang_item(SolverProjectionLangItem::FutureOutput);
624    let future_output_ty =
625        Ty::new_projection(cx, ty::IsRigid::No, future_output_def_id, [sig.output()]);
626    Ok((
627        bound_sig.rebind(AsyncCallableRelevantTypes {
628            tupled_inputs_ty: Ty::new_tup(cx, sig.inputs().as_slice()),
629            output_coroutine_ty: sig.output(),
630            coroutine_return_ty: future_output_ty,
631        }),
632        nested,
633    ))
634}
635
636/// Given a coroutine-closure, project to its returned coroutine when we are *certain*
637/// that the closure's kind is compatible with the goal.
638fn coroutine_closure_to_certain_coroutine<I: Interner>(
639    cx: I,
640    goal_kind: ty::ClosureKind,
641    goal_region: Region<I>,
642    def_id: I::CoroutineClosureId,
643    args: ty::CoroutineClosureArgs<I>,
644    sig: ty::CoroutineClosureSignature<I>,
645) -> I::Ty {
646    sig.to_coroutine_given_kind_and_upvars(
647        cx,
648        args.parent_args(),
649        cx.coroutine_for_closure(def_id),
650        goal_kind,
651        goal_region,
652        args.tupled_upvars_ty(),
653        args.coroutine_captures_by_ref_ty(),
654    )
655}
656
657/// Given a coroutine-closure, project to its returned coroutine when we are *not certain*
658/// that the closure's kind is compatible with the goal, and therefore also don't know
659/// yet what the closure's upvars are.
660///
661/// Note that we do not also push a `AsyncFnKindHelper` goal here.
662fn coroutine_closure_to_ambiguous_coroutine<I: Interner>(
663    cx: I,
664    goal_kind: ty::ClosureKind,
665    goal_region: Region<I>,
666    def_id: I::CoroutineClosureId,
667    args: ty::CoroutineClosureArgs<I>,
668    sig: ty::CoroutineClosureSignature<I>,
669) -> I::Ty {
670    let upvars_projection_def_id =
671        cx.require_projection_lang_item(SolverProjectionLangItem::AsyncFnKindUpvars);
672    let tupled_upvars_ty = Ty::new_projection(
673        cx,
674        ty::IsRigid::No,
675        upvars_projection_def_id,
676        [
677            I::GenericArg::from(args.kind_ty()),
678            Ty::from_closure_kind(cx, goal_kind).into(),
679            goal_region.into(),
680            sig.tupled_inputs_ty.into(),
681            args.tupled_upvars_ty().into(),
682            args.coroutine_captures_by_ref_ty().into(),
683        ],
684    );
685    sig.to_coroutine(
686        cx,
687        args.parent_args(),
688        Ty::from_closure_kind(cx, goal_kind),
689        cx.coroutine_for_closure(def_id),
690        tupled_upvars_ty,
691    )
692}
693
694/// This duplicates `extract_tupled_inputs_and_output_from_callable` but needs
695/// to return different information (namely, the def id and args) so that we can
696/// create const conditions.
697///
698/// Doing so on all calls to `extract_tupled_inputs_and_output_from_callable`
699/// would be wasteful.
700{}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
            ::tracing::Level::TRACE <=
                ::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("extract_fn_def_from_const_callable",
                                "rustc_next_trait_solver::solve::assembly::structural_traits",
                                ::tracing::Level::TRACE,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs"),
                                ::tracing_core::__macro_support::Option::Some(700u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly::structural_traits"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("self_ty")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("self_ty");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::TRACE <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::TRACE <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[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<(ty::Binder<I, (I::Ty, I::Ty)>, I::DefId,
                                I::GenericArgs), NoSolution> = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        match self_ty.kind() {
                            ty::FnDef(def_id, args) => {
                                let args = args.no_bound_vars().unwrap();
                                let sig = cx.fn_sig(def_id);
                                if sig.skip_binder().is_fn_trait_compatible() &&
                                            !cx.has_target_features(def_id) && cx.fn_is_const(def_id) {
                                    Ok((sig.instantiate(cx,
                                                        args).skip_norm_wip().map_bound(|sig|
                                                    (Ty::new_tup(cx, sig.inputs().as_slice()), sig.output())),
                                            def_id.into(), args))
                                } else { return Err(NoSolution); }
                            }
                            ty::FnPtr(..) => { return Err(NoSolution); }
                            ty::Closure(def, args) => {
                                if cx.closure_is_const(def) {
                                    let closure_args = args.as_closure();
                                    Ok((closure_args.sig().map_bound(|sig|
                                                    (sig.inputs().get(0).unwrap(), sig.output())), def.into(),
                                            args))
                                } else { return Err(NoSolution); }
                            }
                            ty::CoroutineClosure(..) => { return Err(NoSolution); }
                            ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) |
                                ty::Float(_) | ty::Adt(_, _) | ty::Foreign(_) | ty::Str |
                                ty::Array(_, _) | ty::Slice(_) | ty::RawPtr(_, _) |
                                ty::Ref(_, _, _) | ty::Dynamic(_, _) | ty::Coroutine(_, _) |
                                ty::CoroutineWitness(..) | ty::Never | ty::Tuple(_) |
                                ty::Pat(_, _) | ty::Alias(ty::IsRigid::Yes, _) |
                                ty::Param(_) | ty::Placeholder(..) |
                                ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) | ty::Error(_) |
                                ty::UnsafeBinder(_) => return Err(NoSolution),
                            ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_)
                                | ty::FreshFloatTy(_)) | ty::Alias(ty::IsRigid::No, _) |
                                ty::Bound(..) => {
                                {
                                    ::core::panicking::panic_fmt(format_args!("unexpected type `{0:?}`",
                                            self_ty));
                                }
                            }
                            ty::View(..) =>
                                ::core::panicking::unimplemented_default_msg(),
                        }
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs:700",
                        "rustc_next_trait_solver::solve::assembly::structural_traits",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs"),
                        ::tracing_core::__macro_support::Option::Some(700u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly::structural_traits"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "trace", skip(cx), ret)]
701pub(in crate::solve) fn extract_fn_def_from_const_callable<I: Interner>(
702    cx: I,
703    self_ty: I::Ty,
704) -> Result<(ty::Binder<I, (I::Ty, I::Ty)>, I::DefId, I::GenericArgs), NoSolution> {
705    match self_ty.kind() {
706        ty::FnDef(def_id, args) => {
707            // FIXME
708            let args = args.no_bound_vars().unwrap();
709
710            let sig = cx.fn_sig(def_id);
711            if sig.skip_binder().is_fn_trait_compatible()
712                && !cx.has_target_features(def_id)
713                && cx.fn_is_const(def_id)
714            {
715                Ok((
716                    sig.instantiate(cx, args)
717                        .skip_norm_wip()
718                        .map_bound(|sig| (Ty::new_tup(cx, sig.inputs().as_slice()), sig.output())),
719                    def_id.into(),
720                    args,
721                ))
722            } else {
723                return Err(NoSolution);
724            }
725        }
726        // `FnPtr`s are not const for now.
727        ty::FnPtr(..) => {
728            return Err(NoSolution);
729        }
730        ty::Closure(def, args) => {
731            if cx.closure_is_const(def) {
732                let closure_args = args.as_closure();
733                Ok((
734                    closure_args
735                        .sig()
736                        .map_bound(|sig| (sig.inputs().get(0).unwrap(), sig.output())),
737                    def.into(),
738                    args,
739                ))
740            } else {
741                return Err(NoSolution);
742            }
743        }
744        // `CoroutineClosure`s are not const for now.
745        ty::CoroutineClosure(..) => {
746            return Err(NoSolution);
747        }
748
749        ty::Bool
750        | ty::Char
751        | ty::Int(_)
752        | ty::Uint(_)
753        | ty::Float(_)
754        | ty::Adt(_, _)
755        | ty::Foreign(_)
756        | ty::Str
757        | ty::Array(_, _)
758        | ty::Slice(_)
759        | ty::RawPtr(_, _)
760        | ty::Ref(_, _, _)
761        | ty::Dynamic(_, _)
762        | ty::Coroutine(_, _)
763        | ty::CoroutineWitness(..)
764        | ty::Never
765        | ty::Tuple(_)
766        | ty::Pat(_, _)
767        | ty::Alias(ty::IsRigid::Yes, _)
768        | ty::Param(_)
769        | ty::Placeholder(..)
770        | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
771        | ty::Error(_)
772        | ty::UnsafeBinder(_) => return Err(NoSolution),
773
774        ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_))
775        | ty::Alias(ty::IsRigid::No, _)
776        | ty::Bound(..) => {
777            panic!("unexpected type `{self_ty:?}`")
778        }
779
780        // FIXME(scrabsha)
781        ty::View(..) => unimplemented!(),
782    }
783}
784
785// NOTE: Keep this in sync with `evaluate_host_effect_for_destruct_goal` in
786// the old solver, for as long as that exists.
787pub(in crate::solve) fn const_conditions_for_destruct<I: Interner>(
788    cx: I,
789    self_ty: I::Ty,
790) -> Result<Vec<ty::TraitRef<I>>, NoSolution> {
791    let destruct_def_id = cx.require_trait_lang_item(SolverTraitLangItem::Destruct);
792
793    match self_ty.kind() {
794        // `ManuallyDrop` is trivially `[const] Destruct` as we do not run any drop glue on it.
795        ty::Adt(adt_def, _) if adt_def.is_manually_drop() => Ok(::alloc::vec::Vec::new()vec![]),
796
797        // An ADT is `[const] Destruct` only if all of the fields are,
798        // *and* if there is a `Drop` impl, that `Drop` impl is also `[const]`.
799        ty::Adt(adt_def, args) => {
800            let mut const_conditions: Vec<_> = adt_def
801                .all_field_tys(cx)
802                .iter_instantiated(cx, args)
803                .map(Unnormalized::skip_norm_wip)
804                .map(|field_ty| ty::TraitRef::new(cx, destruct_def_id, [field_ty]))
805                .collect();
806            match adt_def.destructor(cx) {
807                // `Drop` impl exists, but it's not const. Type cannot be `[const] Destruct`.
808                Some(AdtDestructorKind::NotConst) => return Err(NoSolution),
809                // `Drop` impl exists, and it's const. Require `Ty: [const] Drop` to hold.
810                Some(AdtDestructorKind::Const) => {
811                    let drop_def_id = cx.require_trait_lang_item(SolverTraitLangItem::Drop);
812                    let drop_trait_ref = ty::TraitRef::new(cx, drop_def_id, [self_ty]);
813                    const_conditions.push(drop_trait_ref);
814                }
815                // No `Drop` impl, no need to require anything else.
816                None => {}
817            }
818            Ok(const_conditions)
819        }
820
821        ty::Array(ty, _) | ty::Pat(ty, _) | ty::Slice(ty) => {
822            Ok(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [ty::TraitRef::new(cx, destruct_def_id, [ty])]))vec![ty::TraitRef::new(cx, destruct_def_id, [ty])])
823        }
824
825        ty::Tuple(tys) => Ok(tys
826            .iter()
827            .map(|field_ty| ty::TraitRef::new(cx, destruct_def_id, [field_ty]))
828            .collect()),
829
830        // Trivially implement `[const] Destruct`
831        ty::Bool
832        | ty::Char
833        | ty::Int(..)
834        | ty::Uint(..)
835        | ty::Float(..)
836        | ty::Str
837        | ty::RawPtr(..)
838        | ty::Ref(..)
839        | ty::FnDef(..)
840        | ty::FnPtr(..)
841        | ty::Never
842        | ty::Infer(ty::InferTy::FloatVar(_) | ty::InferTy::IntVar(_))
843        | ty::Error(_) => Ok(::alloc::vec::Vec::new()vec![]),
844
845        // Closures are [const] Destruct when all of their upvars (captures) are [const] Destruct.
846        ty::Closure(_, args) => {
847            let closure_args = args.as_closure();
848            Ok(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [ty::TraitRef::new(cx, destruct_def_id,
                    [closure_args.tupled_upvars_ty()])]))vec![ty::TraitRef::new(cx, destruct_def_id, [closure_args.tupled_upvars_ty()])])
849        }
850        // Coroutines could implement `[const] Drop`,
851        // but they don't really need to right now.
852        ty::CoroutineClosure(_, _) | ty::Coroutine(_, _) | ty::CoroutineWitness(_, _) => {
853            Err(NoSolution)
854        }
855
856        // FIXME(unsafe_binders): Unsafe binders could implement `[const] Drop`
857        // if their inner type implements it.
858        ty::UnsafeBinder(_) => Err(NoSolution),
859
860        ty::Dynamic(..) | ty::Param(_) | ty::Alias(..) | ty::Placeholder(_) | ty::Foreign(_) => {
861            Err(NoSolution)
862        }
863
864        ty::Bound(..)
865        | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
866            {
    ::core::panicking::panic_fmt(format_args!("unexpected type `{0:?}`",
            self_ty));
}panic!("unexpected type `{self_ty:?}`")
867        }
868
869        // FIXME(scrabsha)
870        ty::View(..) => ::core::panicking::unimplemented_default_msg()unimplemented!(),
871    }
872}
873
874/// Assemble a list of predicates that would be present on a theoretical
875/// user impl for an object type. These predicates must be checked any time
876/// we assemble a built-in object candidate for an object type, since they
877/// are not implied by the well-formedness of the type.
878///
879/// For example, given the following traits:
880///
881/// ```rust,ignore (theoretical code)
882/// trait Foo: Baz {
883///     type Bar: Copy;
884/// }
885///
886/// trait Baz {}
887/// ```
888///
889/// For the dyn type `dyn Foo<Item = Ty>`, we can imagine there being a
890/// pair of theoretical impls:
891///
892/// ```rust,ignore (theoretical code)
893/// impl Foo for dyn Foo<Item = Ty>
894/// where
895///     Self: Baz,
896///     <Self as Foo>::Bar: Copy,
897/// {
898///     type Bar = Ty;
899/// }
900///
901/// impl Baz for dyn Foo<Item = Ty> {}
902/// ```
903///
904/// However, in order to make such impls non-cyclical, we need to do an
905/// additional step of eagerly folding the associated types in the where
906/// clauses of the impl. In this example, that means replacing
907/// `<Self as Foo>::Bar` with `Ty` in the first impl.
908pub(in crate::solve) fn predicates_for_object_candidate<D, I>(
909    ecx: &mut EvalCtxt<'_, D>,
910    param_env: I::ParamEnv,
911    trait_ref: ty::TraitRef<I>,
912    object_bounds: I::BoundExistentialPredicates,
913) -> Result<Vec<Goal<I, I::Predicate>>, NoUniqueSolutionOrRerunNonErased>
914where
915    D: SolverDelegate<Interner = I>,
916    I: Interner,
917{
918    let cx = ecx.cx();
919    let mut requirements = ::alloc::vec::Vec::new()vec![];
920    // Elaborating all supertrait outlives obligations here is not soundness critical,
921    // since if we just used the unelaborated set, then the transitive supertraits would
922    // be reachable when proving the former. However, since we elaborate all supertrait
923    // outlives obligations when confirming impls, we would end up with a different set
924    // of outlives obligations here if we didn't do the same, leading to ambiguity.
925    // FIXME(-Znext-solver=coinductive): Adding supertraits here can be removed once we
926    // make impls coinductive always, since they'll always need to prove their supertraits.
927    requirements.extend(elaborate::elaborate(
928        cx,
929        cx.explicit_super_clauses_of(trait_ref.def_id)
930            .iter_instantiated(cx, trait_ref.args)
931            .map(Unnormalized::skip_norm_wip)
932            .map(|(pred, _)| pred),
933    ));
934
935    // FIXME(mgca): Also add associated consts to
936    // the requirements here.
937    for associated_type_def_id in cx.associated_type_def_ids(trait_ref.def_id) {
938        // associated types that require `Self: Sized` do not show up in the built-in
939        // implementation of `Trait for dyn Trait`, and can be dropped here.
940        if cx.generics_require_sized_self(associated_type_def_id) {
941            continue;
942        }
943
944        requirements.extend(
945            cx.item_bounds(associated_type_def_id)
946                .iter_instantiated(cx, trait_ref.args)
947                .map(Unnormalized::skip_norm_wip),
948        );
949    }
950
951    let mut replace_projection_with: HashMap<_, Vec<_>> = HashMap::default();
952    for bound in object_bounds.iter() {
953        if let ty::ExistentialPredicate::Projection(proj) = bound.skip_binder() {
954            // FIXME: We *probably* should replace this with a dummy placeholder,
955            // b/c don't want to replace literal instances of this dyn type that
956            // show up in the bounds, but just ones that come from substituting
957            // `Self` with the dyn type.
958            let proj = proj.with_self_ty(cx, trait_ref.self_ty());
959            let bound = ecx.normalize(param_env, Unnormalized::new_wip(bound.rebind(proj)))?;
960            replace_projection_with.entry(proj.def_id()).or_default().push(bound);
961        }
962    }
963
964    let mut folder = ReplaceProjectionWith {
965        ecx,
966        param_env,
967        self_ty: trait_ref.self_ty(),
968        mapping: &replace_projection_with,
969        nested: ::alloc::vec::Vec::new()vec![],
970    };
971
972    let requirements = requirements.try_fold_with(&mut folder)?;
973    Ok(folder
974        .nested
975        .into_iter()
976        .chain(requirements.into_iter().map(|clause| Goal::new(cx, param_env, clause)))
977        .collect())
978}
979
980struct ReplaceProjectionWith<'a, 'b, I: Interner, D: SolverDelegate<Interner = I>> {
981    ecx: &'a mut EvalCtxt<'b, D>,
982    param_env: I::ParamEnv,
983    self_ty: I::Ty,
984    mapping: &'a HashMap<I::TraitAssocTermId, Vec<ty::Binder<I, ty::ProjectionClause<I>>>>,
985    nested: Vec<Goal<I, I::Predicate>>,
986}
987
988impl<D, I> ReplaceProjectionWith<'_, '_, I, D>
989where
990    D: SolverDelegate<Interner = I>,
991    I: Interner,
992{
993    fn projection_may_match(
994        &mut self,
995        source_projection: ty::Binder<I, ty::ProjectionClause<I>>,
996        target_projection: ty::AliasTerm<I>,
997    ) -> Result<bool, RerunNonErased> {
998        if source_projection.item_def_id() != target_projection.expect_projection_def_id() {
999            return Ok(false);
1000        }
1001        match self
1002            .ecx
1003            .probe(|_| ProbeKind::ProjectionCompatibility)
1004            .enter_without_propagated_nested_goals(|ecx| {
1005                let source_projection = ecx.instantiate_binder_with_infer(source_projection);
1006                ecx.eq(self.param_env, source_projection.projection_term, target_projection)?;
1007                ecx.try_evaluate_added_goals()
1008            }) {
1009            Ok(_) => Ok(true),
1010            Err(NoSolutionOrRerunNonErased::NoSolution(_)) => Ok(false),
1011            Err(NoSolutionOrRerunNonErased::RerunNonErased(rerun)) => Err(rerun),
1012        }
1013    }
1014
1015    /// Try to replace an alias with the term present in the projection bounds of the self type.
1016    /// Returns `Ok<None>` if this alias is not eligible to be replaced, or bail with
1017    /// `Err(NoSolution)` if the alias is ill-formed or cannot be normalized, or bail with
1018    /// `Err(Ambiguous)` if it's uncertain which projection bound to replace the term with due
1019    /// to multiple bounds applying, or with `Err(RerunNonErased)` if we have to rerun the
1020    /// goal in original `TypingMode`.
1021    fn try_eagerly_replace_alias(
1022        &mut self,
1023        alias_term: ty::AliasTerm<I>,
1024    ) -> Result<Option<I::Term>, NoUniqueSolutionOrRerunNonErased> {
1025        if alias_term.self_ty() != self.self_ty {
1026            return Ok(None);
1027        }
1028
1029        let Some(replacements) = self.mapping.get(&alias_term.expect_projection_def_id()) else {
1030            return Ok(None);
1031        };
1032
1033        // We don't normalize this inside `predicates_for_object_candidates` but here
1034        // because we structurally match the projection here with the bounds so we
1035        // don't want the projection itself is replaced by infer var but only its
1036        // args.
1037        let alias_term = self.ecx.normalize(self.param_env, Unnormalized::new_wip(alias_term))?;
1038
1039        // This is quite similar to the `projection_may_match` we use in unsizing,
1040        // but here we want to unify a projection predicate against an alias term
1041        // so we can replace it with the projection predicate's term.
1042        let mut matching_projection = None;
1043        for source_projection in replacements {
1044            if self.projection_may_match(*source_projection, alias_term)? {
1045                // FIXME: This *may* have issues with duplicated projections.
1046                if matching_projection.is_some() {
1047                    // If there's more than one projection that we can unify here, then we
1048                    // need to stall until inference constrains things so that there's only
1049                    // one choice.
1050                    return Err(NoUniqueSolutionOrRerunNonErased::Ambiguous);
1051                }
1052                matching_projection = Some(source_projection)
1053            }
1054        }
1055
1056        let Some(matching) = matching_projection else {
1057            // This shouldn't happen.
1058            {
    ::core::panicking::panic_fmt(format_args!("could not replace {1:?} with term from from {0:?}",
            self.self_ty, alias_term));
};panic!("could not replace {alias_term:?} with term from from {:?}", self.self_ty);
1059        };
1060
1061        let replacement = self.ecx.instantiate_binder_with_infer(*matching);
1062        self.nested.extend(
1063            self.ecx
1064                .eq_and_get_goals(self.param_env, alias_term, replacement.projection_term)
1065                .expect("expected to be able to unify goal projection with dyn's projection"),
1066        );
1067
1068        Ok(Some(replacement.term))
1069    }
1070}
1071
1072pub(crate) enum NoUniqueSolutionOrRerunNonErased {
1073    /// Marker for bailing with ambiguity.
1074    Ambiguous,
1075    NoSolution(NoSolution),
1076    RerunNonErased(RerunNonErased),
1077}
1078
1079impl From<RerunNonErased> for NoUniqueSolutionOrRerunNonErased {
1080    fn from(rerun: RerunNonErased) -> Self {
1081        NoUniqueSolutionOrRerunNonErased::RerunNonErased(rerun)
1082    }
1083}
1084
1085impl From<NoSolutionOrRerunNonErased> for NoUniqueSolutionOrRerunNonErased {
1086    fn from(value: NoSolutionOrRerunNonErased) -> Self {
1087        match value {
1088            NoSolutionOrRerunNonErased::NoSolution(no_solution) => {
1089                NoUniqueSolutionOrRerunNonErased::NoSolution(no_solution)
1090            }
1091            NoSolutionOrRerunNonErased::RerunNonErased(rerun) => {
1092                NoUniqueSolutionOrRerunNonErased::RerunNonErased(rerun)
1093            }
1094        }
1095    }
1096}
1097
1098impl<D, I> FallibleTypeFolder<I> for ReplaceProjectionWith<'_, '_, I, D>
1099where
1100    D: SolverDelegate<Interner = I>,
1101    I: Interner,
1102{
1103    type Error = NoUniqueSolutionOrRerunNonErased;
1104
1105    fn cx(&self) -> I {
1106        self.ecx.cx()
1107    }
1108
1109    fn try_fold_ty(&mut self, ty: I::Ty) -> Result<I::Ty, Self::Error> {
1110        if let ty::Alias(_, alias_ty @ ty::AliasTy { kind: ty::Projection { .. }, .. }) = ty.kind()
1111            && let Some(term) = self.try_eagerly_replace_alias(alias_ty.into())?
1112        {
1113            Ok(term.expect_ty())
1114        } else {
1115            ty.try_super_fold_with(self)
1116        }
1117    }
1118}