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