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