Skip to main content

rustc_ty_utils/
ty.rs

1use rustc_data_structures::fx::FxHashSet;
2use rustc_hir as hir;
3use rustc_hir::def::DefKind;
4use rustc_index::bit_set::DenseBitSet;
5use rustc_infer::infer::TyCtxtInferExt;
6use rustc_middle::query::Providers;
7use rustc_middle::ty::{
8    self, SizedTraitKind, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitor, Unnormalized,
9    Upcast, fold_regions,
10};
11use rustc_span::def_id::{CRATE_DEF_ID, DefId, LocalDefId};
12use rustc_span::{DUMMY_SP, bug};
13use rustc_trait_selection::traits;
14use tracing::instrument;
15
16/// If `ty` implements the given `sizedness` trait, returns `None`. Otherwise, returns the type
17/// that must implement the given `sizedness` for `ty` to implement it.
18{}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
            ::tracing::Level::DEBUG <=
                ::tracing::level_filters::LevelFilter::current() || { false }
    {
    __tracing_attr_span =
        {
            use ::tracing::__macro_support::Callsite as _;
            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                {
                    static META: ::tracing::Metadata<'static> =
                        {
                            ::tracing_core::metadata::Metadata::new("sizedness_constraint_for_ty",
                                "rustc_ty_utils::ty", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_ty_utils/src/ty.rs"),
                                ::tracing_core::__macro_support::Option::Some(18u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::ty"),
                                ::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::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&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: Option<Ty<'tcx>> = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        match ty.kind() {
                            ty::Bool | ty::Char | ty::Int(..) | ty::Uint(..) |
                                ty::Float(..) | ty::RawPtr(..) | ty::Ref(..) | ty::FnDef(..)
                                | ty::FnPtr(..) | ty::Array(..) | ty::Closure(..) |
                                ty::CoroutineClosure(..) | ty::Coroutine(..) |
                                ty::CoroutineWitness(..) | ty::Never => None,
                            ty::Str | ty::Slice(..) | ty::Dynamic(_, _) =>
                                match sizedness {
                                    SizedTraitKind::Sized => Some(ty),
                                    SizedTraitKind::MetaSized => None,
                                },
                            ty::Param(..) | ty::Alias(..) | ty::Error(_) => Some(ty),
                            ty::UnsafeBinder(inner_ty) => {
                                sizedness_constraint_for_ty(tcx, sizedness,
                                        inner_ty.skip_binder()).map(|_| ty)
                            }
                            ty::Foreign(..) => Some(ty),
                            ty::Pat(ty, _) =>
                                sizedness_constraint_for_ty(tcx, sizedness, *ty),
                            ty::Tuple(tys) => {
                                tys.last().and_then(|&ty|
                                        sizedness_constraint_for_ty(tcx, sizedness, ty))
                            }
                            ty::Adt(adt, args) =>
                                adt.sizedness_constraint(tcx,
                                        sizedness).and_then(|intermediate|
                                        {
                                            let ty =
                                                intermediate.instantiate(tcx, args).skip_norm_wip();
                                            sizedness_constraint_for_ty(tcx, sizedness, ty)
                                        }),
                            ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) => {
                                ::rustc_span::macros::bug_impl(None,
                                    format_args!("unexpected type `{0:?}` in `sizedness_constraint_for_ty`",
                                        ty), Location::caller())
                            }
                            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/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_ty_utils/src/ty.rs:18",
                        "rustc_ty_utils::ty", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_ty_utils/src/ty.rs"),
                        ::tracing_core::__macro_support::Option::Some(18u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::ty"),
                        ::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::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "debug", skip(tcx), ret)]
19fn sizedness_constraint_for_ty<'tcx>(
20    tcx: TyCtxt<'tcx>,
21    sizedness: SizedTraitKind,
22    ty: Ty<'tcx>,
23) -> Option<Ty<'tcx>> {
24    match ty.kind() {
25        // Always `Sized` or `MetaSized`
26        ty::Bool
27        | ty::Char
28        | ty::Int(..)
29        | ty::Uint(..)
30        | ty::Float(..)
31        | ty::RawPtr(..)
32        | ty::Ref(..)
33        | ty::FnDef(..)
34        | ty::FnPtr(..)
35        | ty::Array(..)
36        | ty::Closure(..)
37        | ty::CoroutineClosure(..)
38        | ty::Coroutine(..)
39        | ty::CoroutineWitness(..)
40        | ty::Never => None,
41
42        ty::Str | ty::Slice(..) | ty::Dynamic(_, _) => match sizedness {
43            // Never `Sized`
44            SizedTraitKind::Sized => Some(ty),
45            // Always `MetaSized`
46            SizedTraitKind::MetaSized => None,
47        },
48
49        // Maybe `Sized` or `MetaSized`
50        ty::Param(..) | ty::Alias(..) | ty::Error(_) => Some(ty),
51
52        // We cannot instantiate the binder, so just return the *original* type back,
53        // but only if the inner type has a sized constraint. Thus we skip the binder,
54        // but don't actually use the result from `sized_constraint_for_ty`.
55        ty::UnsafeBinder(inner_ty) => {
56            sizedness_constraint_for_ty(tcx, sizedness, inner_ty.skip_binder()).map(|_| ty)
57        }
58
59        // Never `MetaSized` or `Sized`
60        ty::Foreign(..) => Some(ty),
61
62        // Recursive cases
63        ty::Pat(ty, _) => sizedness_constraint_for_ty(tcx, sizedness, *ty),
64
65        ty::Tuple(tys) => {
66            tys.last().and_then(|&ty| sizedness_constraint_for_ty(tcx, sizedness, ty))
67        }
68
69        ty::Adt(adt, args) => adt.sizedness_constraint(tcx, sizedness).and_then(|intermediate| {
70            let ty = intermediate.instantiate(tcx, args).skip_norm_wip();
71            sizedness_constraint_for_ty(tcx, sizedness, ty)
72        }),
73
74        ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) => {
75            bug!("unexpected type `{ty:?}` in `sizedness_constraint_for_ty`")
76        }
77
78        // FIXME(scrabsha)
79        ty::View(..) => unimplemented!(),
80    }
81}
82
83fn defaultness(tcx: TyCtxt<'_>, def_id: LocalDefId) -> hir::Defaultness {
84    match tcx.hir_node_by_def_id(def_id) {
85        hir::Node::Item(hir::Item {
86            kind:
87                hir::ItemKind::Impl(hir::Impl {
88                    of_trait: Some(hir::TraitImplHeader { defaultness, .. }),
89                    ..
90                }),
91            ..
92        })
93        | hir::Node::ImplItem(hir::ImplItem {
94            impl_kind: hir::ImplItemImplKind::Trait { defaultness, .. },
95            ..
96        })
97        | hir::Node::TraitItem(hir::TraitItem { defaultness, .. }) => *defaultness,
98        node => {
99            ::rustc_span::macros::bug_impl(None,
    format_args!("`defaultness` called on {0:?}", node), Location::caller());bug!("`defaultness` called on {:?}", node);
100        }
101    }
102}
103
104/// Returns the type of the last field of a struct ("the constraint") which must implement the
105/// `sizedness` trait for the whole ADT to be considered to implement that `sizedness` trait.
106/// `def_id` is assumed to be the `AdtDef` of a struct and will panic otherwise.
107///
108/// For `Sized`, there are only a few options for the types in the constraint:
109///     - an meta-sized type (str, slices, trait objects, etc)
110///     - an pointee-sized type (extern types)
111///     - a type parameter or projection whose sizedness can't be known
112///
113/// For `MetaSized`, there are only a few options for the types in the constraint:
114///     - an pointee-sized type (extern types)
115///     - a type parameter or projection whose sizedness can't be known
116{}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
            ::tracing::Level::DEBUG <=
                ::tracing::level_filters::LevelFilter::current() || { false }
    {
    __tracing_attr_span =
        {
            use ::tracing::__macro_support::Callsite as _;
            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                {
                    static META: ::tracing::Metadata<'static> =
                        {
                            ::tracing_core::metadata::Metadata::new("adt_sizedness_constraint",
                                "rustc_ty_utils::ty", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_ty_utils/src/ty.rs"),
                                ::tracing_core::__macro_support::Option::Some(116u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::ty"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("def_id")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("def_id");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("sizedness")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("sizedness");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sizedness)
                                                        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:
                                Option<ty::EarlyBinder<'tcx, Ty<'tcx>>> = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        if let Some(def_id) = def_id.as_local() {
                            tcx.ensure_ok().check_representability(def_id);
                        }
                        let def = tcx.adt_def(def_id);
                        if !def.is_struct() {
                            ::rustc_span::macros::bug_impl(None,
                                format_args!("`adt_sizedness_constraint` called on non-struct type: {0:?}",
                                    def), Location::caller());
                        }
                        let tail_def = def.non_enum_variant().tail_opt()?;
                        let tail_ty =
                            tcx.type_of(tail_def.did).instantiate_identity().skip_norm_wip();
                        let constraint_ty =
                            sizedness_constraint_for_ty(tcx, sizedness, tail_ty)?;
                        let sizedness_trait_def_id =
                            sizedness.require_lang_item(tcx);
                        let clauses = tcx.clauses_of(def.did()).clauses;
                        if clauses.iter().any(|(c, _)|
                                    {
                                        c.as_trait_clause().is_some_and(|trait_pred|
                                                {
                                                    trait_pred.def_id() == sizedness_trait_def_id &&
                                                        trait_pred.self_ty().skip_binder() == constraint_ty
                                                })
                                    }) {
                            return None;
                        }
                        Some(ty::EarlyBinder::bind(tcx, constraint_ty))
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_ty_utils/src/ty.rs:116",
                        "rustc_ty_utils::ty", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_ty_utils/src/ty.rs"),
                        ::tracing_core::__macro_support::Option::Some(116u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::ty"),
                        ::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::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "debug", skip(tcx), ret)]
117fn adt_sizedness_constraint<'tcx>(
118    tcx: TyCtxt<'tcx>,
119    (def_id, sizedness): (DefId, SizedTraitKind),
120) -> Option<ty::EarlyBinder<'tcx, Ty<'tcx>>> {
121    if let Some(def_id) = def_id.as_local() {
122        tcx.ensure_ok().check_representability(def_id);
123    }
124
125    let def = tcx.adt_def(def_id);
126
127    if !def.is_struct() {
128        bug!("`adt_sizedness_constraint` called on non-struct type: {def:?}");
129    }
130
131    let tail_def = def.non_enum_variant().tail_opt()?;
132    let tail_ty = tcx.type_of(tail_def.did).instantiate_identity().skip_norm_wip();
133
134    let constraint_ty = sizedness_constraint_for_ty(tcx, sizedness, tail_ty)?;
135
136    // perf hack: if there is a `constraint_ty: {Meta,}Sized` bound, then we know
137    // that the type is sized and do not need to check it on the impl.
138    let sizedness_trait_def_id = sizedness.require_lang_item(tcx);
139    let clauses = tcx.clauses_of(def.did()).clauses;
140    if clauses.iter().any(|(c, _)| {
141        c.as_trait_clause().is_some_and(|trait_pred| {
142            trait_pred.def_id() == sizedness_trait_def_id
143                && trait_pred.self_ty().skip_binder() == constraint_ty
144        })
145    }) {
146        return None;
147    }
148
149    Some(ty::EarlyBinder::bind(tcx, constraint_ty))
150}
151
152/// See `ParamEnv` struct definition for details.
153fn param_env(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> {
154    if tcx.is_typeck_child(def_id) {
155        return tcx.param_env(tcx.typeck_root_def_id(def_id));
156    }
157    // Compute the bounds on Self and the type parameters.
158    let ty::InstantiatedClauses { clauses, .. } = tcx.clauses_of(def_id).instantiate_identity(tcx);
159    let mut clauses: Vec<_> = clauses.into_iter().map(Unnormalized::skip_norm_wip).collect();
160
161    // Finally, we have to normalize the bounds in the environment, in
162    // case they contain any associated type projections. This process
163    // can yield errors if the put in illegal associated types, like
164    // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
165    // report these errors right here; this doesn't actually feel
166    // right to me, because constructing the environment feels like a
167    // kind of an "idempotent" action, but I'm not sure where would be
168    // a better place. In practice, we construct environments for
169    // every fn once during type checking, and we'll abort if there
170    // are any errors at that point, so outside of type inference you can be
171    // sure that this will succeed without errors anyway.
172
173    if tcx.def_kind(def_id) == DefKind::AssocFn
174        && let assoc_item = tcx.associated_item(def_id)
175        && assoc_item.container == ty::AssocContainer::Trait
176        && assoc_item.defaultness(tcx).has_value()
177    {
178        let sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
179        // We accounted for the binder of the fn sig, so skip the binder.
180        sig.skip_binder().visit_with(&mut ImplTraitInTraitFinder {
181            tcx,
182            fn_def_id: def_id,
183            bound_vars: sig.bound_vars(),
184            clauses: &mut clauses,
185            seen: FxHashSet::default(),
186            depth: ty::INNERMOST,
187        });
188    }
189
190    // We extend the param-env of our item with the const conditions of the item,
191    // since we're allowed to assume `[const]` bounds hold within the item itself.
192    if tcx.is_conditionally_const(def_id) {
193        clauses.extend(tcx.const_conditions(def_id).instantiate_identity(tcx).into_iter().map(
194            |(trait_ref, _)| {
195                trait_ref.to_host_effect_clause(tcx, ty::BoundConstness::Maybe).skip_norm_wip()
196            },
197        ));
198    }
199
200    let local_did = def_id.as_local().unwrap_or(CRATE_DEF_ID);
201
202    let cause = traits::ObligationCause::misc(tcx.def_span(def_id), local_did);
203    traits::normalize_param_env_or_error(tcx, clauses, cause)
204}
205
206/// Walk through a function type, gathering all RPITITs and installing a
207/// `NormalizesTo(Projection(RPITIT) -> Opaque(RPITIT))` predicate into the
208/// predicates list. This allows us to observe that an RPITIT projects to
209/// its corresponding opaque within the body of a default-body trait method.
210struct ImplTraitInTraitFinder<'a, 'tcx> {
211    tcx: TyCtxt<'tcx>,
212    clauses: &'a mut Vec<ty::Clause<'tcx>>,
213    fn_def_id: DefId,
214    bound_vars: &'tcx ty::List<ty::BoundVariableKind<'tcx>>,
215    seen: FxHashSet<DefId>,
216    depth: ty::DebruijnIndex,
217}
218
219impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ImplTraitInTraitFinder<'_, 'tcx> {
220    fn visit_binder<T: TypeVisitable<TyCtxt<'tcx>>>(&mut self, binder: &ty::Binder<'tcx, T>) {
221        self.depth.shift_in(1);
222        binder.super_visit_with(self);
223        self.depth.shift_out(1);
224    }
225
226    fn visit_ty(&mut self, ty: Ty<'tcx>) {
227        if let ty::Alias(_, unshifted_alias_ty) = *ty.kind()
228            && let Some(unshifted_alias_ty) = unshifted_alias_ty.try_to_projection()
229            && let Some(
230                ty::ImplTraitInTraitData::Trait { fn_def_id, .. }
231                | ty::ImplTraitInTraitData::Impl { fn_def_id, .. },
232            ) = self.tcx.opt_rpitit_info(unshifted_alias_ty.kind)
233            && fn_def_id == self.fn_def_id
234            && self.seen.insert(unshifted_alias_ty.kind)
235        {
236            // We have entered some binders as we've walked into the
237            // bounds of the RPITIT. Shift these binders back out when
238            // constructing the top-level projection predicate.
239            let shifted_alias_ty = fold_regions(self.tcx, unshifted_alias_ty, |re, depth| {
240                if let ty::ReBound(ty::BoundVarIndexKind::Bound(index), bv) = re.kind() {
241                    if depth != ty::INNERMOST {
242                        return ty::Region::new_error_with_message(
243                            self.tcx,
244                            DUMMY_SP,
245                            "we shouldn't walk non-predicate binders with `impl Trait`...",
246                        );
247                    }
248                    ty::Region::new_bound(self.tcx, index.shifted_out_to_binder(self.depth), bv)
249                } else {
250                    re
251                }
252            });
253
254            // If we're lowering to associated item, install the opaque type which is just
255            // the `type_of` of the trait's associated item. If we're using the old lowering
256            // strategy, then just reinterpret the associated type like an opaque :^)
257            let default_ty = self
258                .tcx
259                .type_of(shifted_alias_ty.kind)
260                .instantiate(self.tcx, shifted_alias_ty.args)
261                .skip_norm_wip();
262
263            self.clauses.push(
264                ty::Binder::bind_with_vars(
265                    ty::ProjectionClause {
266                        projection_term: shifted_alias_ty.projection_to_alias_ty().into(),
267                        term: default_ty.into(),
268                    },
269                    self.bound_vars,
270                )
271                .upcast(self.tcx),
272            );
273
274            // We walk the *un-shifted* alias ty, because we're tracking the de bruijn
275            // binder depth, and if we were to walk `shifted_alias_ty` instead, we'd
276            // have to reset `self.depth` back to `ty::INNERMOST` or something. It's
277            // easier to just do this.
278            for bound in self
279                .tcx
280                .item_bounds(unshifted_alias_ty.kind)
281                .iter_instantiated(self.tcx, unshifted_alias_ty.args)
282                .map(Unnormalized::skip_norm_wip)
283            {
284                bound.visit_with(self);
285            }
286        }
287
288        ty.super_visit_with(self)
289    }
290}
291
292fn param_env_normalized_for_post_analysis(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> {
293    tcx.param_env(def_id).with_normalized(tcx)
294}
295
296/// Check if a function is async.
297fn asyncness(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Asyncness {
298    let node = tcx.hir_node_by_def_id(def_id);
299    node.fn_sig().map_or(ty::Asyncness::No, |sig| match sig.header.asyncness {
300        hir::IsAsync::Async(_) => ty::Asyncness::Yes,
301        hir::IsAsync::NotAsync => ty::Asyncness::No,
302    })
303}
304
305fn unsizing_params_for_adt<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> DenseBitSet<u32> {
306    let def = tcx.adt_def(def_id);
307    let num_params = tcx.generics_of(def_id).count();
308
309    let maybe_unsizing_param_idx = |arg: ty::GenericArg<'tcx>| match arg.kind() {
310        ty::GenericArgKind::Type(ty) => match ty.kind() {
311            ty::Param(p) => Some(p.index),
312            _ => None,
313        },
314
315        // We can't unsize a lifetime
316        ty::GenericArgKind::Lifetime(_) => None,
317
318        ty::GenericArgKind::Const(ct) => match ct.kind() {
319            ty::ConstKind::Param(p) => Some(p.index),
320            _ => None,
321        },
322    };
323
324    // The last field of the structure has to exist and contain type/const parameters.
325    let Some((tail_field, prefix_fields)) = def.non_enum_variant().fields.raw.split_last() else {
326        return DenseBitSet::new_empty(num_params);
327    };
328
329    let mut unsizing_params = DenseBitSet::new_empty(num_params);
330    for arg in tcx.type_of(tail_field.did).instantiate_identity().skip_norm_wip().walk() {
331        if let Some(i) = maybe_unsizing_param_idx(arg) {
332            unsizing_params.insert(i);
333        }
334    }
335
336    // Ensure none of the other fields mention the parameters used
337    // in unsizing.
338    for field in prefix_fields {
339        for arg in tcx.type_of(field.did).instantiate_identity().skip_norm_wip().walk() {
340            if let Some(i) = maybe_unsizing_param_idx(arg) {
341                unsizing_params.remove(i);
342            }
343        }
344    }
345
346    unsizing_params
347}
348
349fn impl_self_is_guaranteed_unsized<'tcx>(tcx: TyCtxt<'tcx>, impl_def_id: DefId) -> bool {
350    if true {
    {
        match (&tcx.def_kind(impl_def_id), &DefKind::Impl { of_trait: true })
            {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(tcx.def_kind(impl_def_id), DefKind::Impl { of_trait: true });
351
352    let infcx = tcx.infer_ctxt().ignoring_regions().build(ty::TypingMode::non_body_analysis());
353
354    let ocx = traits::ObligationCtxt::new(&infcx);
355    let cause = traits::ObligationCause::dummy();
356    let param_env = tcx.param_env(impl_def_id);
357
358    let self_ty = ocx.normalize(&cause, param_env, tcx.type_of(impl_def_id).instantiate_identity());
359    let tail = tcx.struct_tail_raw(
360        self_ty,
361        &cause,
362        |ty| {
363            // FIXME: ambiguity is just ignored.
364            ocx.normalize(&cause, param_env, ty)
365        },
366        || (),
367    );
368
369    match tail.kind() {
370        ty::Dynamic(_, _) | ty::Slice(_) | ty::Str => true,
371        ty::Bool
372        | ty::Char
373        | ty::Int(_)
374        | ty::Uint(_)
375        | ty::Float(_)
376        | ty::Adt(_, _)
377        | ty::Foreign(_)
378        | ty::Array(_, _)
379        | ty::Pat(_, _)
380        | ty::RawPtr(_, _)
381        | ty::Ref(_, _, _)
382        | ty::FnDef(_, _)
383        | ty::FnPtr(_, _)
384        | ty::UnsafeBinder(_)
385        | ty::Closure(_, _)
386        | ty::CoroutineClosure(_, _)
387        | ty::Coroutine(_, _)
388        | ty::CoroutineWitness(_, _)
389        | ty::Never
390        | ty::Tuple(_)
391        | ty::Alias(_, _)
392        | ty::Param(_)
393        | ty::Bound(_, _)
394        | ty::Placeholder(_)
395        | ty::Infer(_)
396        | ty::Error(_) => false,
397
398        // FIXME(scrabsha)
399        ty::View(..) => ::core::panicking::unimplemented_default_msg()unimplemented!(),
400    }
401}
402
403pub(crate) fn provide(providers: &mut Providers) {
404    *providers = Providers {
405        asyncness,
406        adt_sizedness_constraint,
407        param_env,
408        param_env_normalized_for_post_analysis,
409        defaultness,
410        unsizing_params_for_adt,
411        impl_self_is_guaranteed_unsized,
412        ..*providers
413    };
414}