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