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