rustc_ty_utils/
ty.rs

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