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#[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 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 SizedTraitKind::Sized => Some(ty),
46 SizedTraitKind::MetaSized => None,
48 },
49
50 ty::Param(..) | ty::Alias(..) | ty::Error(_) => Some(ty),
52
53 ty::UnsafeBinder(inner_ty) => {
57 sizedness_constraint_for_ty(tcx, sizedness, inner_ty.skip_binder()).map(|_| ty)
58 }
59
60 ty::Foreign(..) => Some(ty),
62
63 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: hir::ItemKind::Impl(hir::Impl { defaultness, of_trait: Some(_), .. }),
85 ..
86 })
87 | hir::Node::ImplItem(hir::ImplItem { defaultness, .. })
88 | hir::Node::TraitItem(hir::TraitItem { defaultness, .. }) => *defaultness,
89 node => {
90 bug!("`defaultness` called on {:?}", node);
91 }
92 }
93}
94
95#[instrument(level = "debug", skip(tcx), ret)]
108fn adt_sizedness_constraint<'tcx>(
109 tcx: TyCtxt<'tcx>,
110 (def_id, sizedness): (DefId, SizedTraitKind),
111) -> Option<ty::EarlyBinder<'tcx, Ty<'tcx>>> {
112 if let Some(def_id) = def_id.as_local()
113 && let ty::Representability::Infinite(_) = tcx.representability(def_id)
114 {
115 return None;
116 }
117 let def = tcx.adt_def(def_id);
118
119 if !def.is_struct() {
120 bug!("`adt_sizedness_constraint` called on non-struct type: {def:?}");
121 }
122
123 let tail_def = def.non_enum_variant().tail_opt()?;
124 let tail_ty = tcx.type_of(tail_def.did).instantiate_identity();
125
126 let constraint_ty = sizedness_constraint_for_ty(tcx, sizedness, tail_ty)?;
127
128 let sizedness_trait_def_id = sizedness.require_lang_item(tcx);
131 let predicates = tcx.predicates_of(def.did()).predicates;
132 if predicates.iter().any(|(p, _)| {
133 p.as_trait_clause().is_some_and(|trait_pred| {
134 trait_pred.def_id() == sizedness_trait_def_id
135 && trait_pred.self_ty().skip_binder() == constraint_ty
136 })
137 }) {
138 return None;
139 }
140
141 Some(ty::EarlyBinder::bind(constraint_ty))
142}
143
144fn param_env(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> {
146 let ty::InstantiatedPredicates { mut predicates, .. } =
148 tcx.predicates_of(def_id).instantiate_identity(tcx);
149
150 if tcx.def_kind(def_id) == DefKind::AssocFn
163 && let assoc_item = tcx.associated_item(def_id)
164 && assoc_item.container == ty::AssocItemContainer::Trait
165 && assoc_item.defaultness(tcx).has_value()
166 {
167 let sig = tcx.fn_sig(def_id).instantiate_identity();
168 sig.skip_binder().visit_with(&mut ImplTraitInTraitFinder {
170 tcx,
171 fn_def_id: def_id,
172 bound_vars: sig.bound_vars(),
173 predicates: &mut predicates,
174 seen: FxHashSet::default(),
175 depth: ty::INNERMOST,
176 });
177 }
178
179 if tcx.is_conditionally_const(def_id) {
182 predicates.extend(
183 tcx.const_conditions(def_id).instantiate_identity(tcx).into_iter().map(
184 |(trait_ref, _)| trait_ref.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
185 ),
186 );
187 }
188
189 let local_did = def_id.as_local();
190
191 let unnormalized_env = ty::ParamEnv::new(tcx.mk_clauses(&predicates));
192
193 let body_id = local_did.unwrap_or(CRATE_DEF_ID);
194 let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
195 traits::normalize_param_env_or_error(tcx, unnormalized_env, cause)
196}
197
198struct ImplTraitInTraitFinder<'a, 'tcx> {
203 tcx: TyCtxt<'tcx>,
204 predicates: &'a mut Vec<ty::Clause<'tcx>>,
205 fn_def_id: DefId,
206 bound_vars: &'tcx ty::List<ty::BoundVariableKind>,
207 seen: FxHashSet<DefId>,
208 depth: ty::DebruijnIndex,
209}
210
211impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ImplTraitInTraitFinder<'_, 'tcx> {
212 fn visit_binder<T: TypeVisitable<TyCtxt<'tcx>>>(&mut self, binder: &ty::Binder<'tcx, T>) {
213 self.depth.shift_in(1);
214 binder.super_visit_with(self);
215 self.depth.shift_out(1);
216 }
217
218 fn visit_ty(&mut self, ty: Ty<'tcx>) {
219 if let ty::Alias(ty::Projection, unshifted_alias_ty) = *ty.kind()
220 && let Some(
221 ty::ImplTraitInTraitData::Trait { fn_def_id, .. }
222 | ty::ImplTraitInTraitData::Impl { fn_def_id, .. },
223 ) = self.tcx.opt_rpitit_info(unshifted_alias_ty.def_id)
224 && fn_def_id == self.fn_def_id
225 && self.seen.insert(unshifted_alias_ty.def_id)
226 {
227 let shifted_alias_ty = fold_regions(self.tcx, unshifted_alias_ty, |re, depth| {
231 if let ty::ReBound(index, bv) = re.kind() {
232 if depth != ty::INNERMOST {
233 return ty::Region::new_error_with_message(
234 self.tcx,
235 DUMMY_SP,
236 "we shouldn't walk non-predicate binders with `impl Trait`...",
237 );
238 }
239 ty::Region::new_bound(self.tcx, index.shifted_out_to_binder(self.depth), bv)
240 } else {
241 re
242 }
243 });
244
245 let default_ty = self
249 .tcx
250 .type_of(shifted_alias_ty.def_id)
251 .instantiate(self.tcx, shifted_alias_ty.args);
252
253 self.predicates.push(
254 ty::Binder::bind_with_vars(
255 ty::ProjectionPredicate {
256 projection_term: shifted_alias_ty.into(),
257 term: default_ty.into(),
258 },
259 self.bound_vars,
260 )
261 .upcast(self.tcx),
262 );
263
264 for bound in self
269 .tcx
270 .item_bounds(unshifted_alias_ty.def_id)
271 .iter_instantiated(self.tcx, unshifted_alias_ty.args)
272 {
273 bound.visit_with(self);
274 }
275 }
276
277 ty.super_visit_with(self)
278 }
279}
280
281fn typing_env_normalized_for_post_analysis(tcx: TyCtxt<'_>, def_id: DefId) -> ty::TypingEnv<'_> {
282 ty::TypingEnv::non_body_analysis(tcx, def_id).with_post_analysis_normalized(tcx)
283}
284
285fn asyncness(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Asyncness {
287 let node = tcx.hir_node_by_def_id(def_id);
288 node.fn_sig().map_or(ty::Asyncness::No, |sig| match sig.header.asyncness {
289 hir::IsAsync::Async(_) => ty::Asyncness::Yes,
290 hir::IsAsync::NotAsync => ty::Asyncness::No,
291 })
292}
293
294fn unsizing_params_for_adt<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> DenseBitSet<u32> {
295 let def = tcx.adt_def(def_id);
296 let num_params = tcx.generics_of(def_id).count();
297
298 let maybe_unsizing_param_idx = |arg: ty::GenericArg<'tcx>| match arg.kind() {
299 ty::GenericArgKind::Type(ty) => match ty.kind() {
300 ty::Param(p) => Some(p.index),
301 _ => None,
302 },
303
304 ty::GenericArgKind::Lifetime(_) => None,
306
307 ty::GenericArgKind::Const(ct) => match ct.kind() {
308 ty::ConstKind::Param(p) => Some(p.index),
309 _ => None,
310 },
311 };
312
313 let Some((tail_field, prefix_fields)) = def.non_enum_variant().fields.raw.split_last() else {
315 return DenseBitSet::new_empty(num_params);
316 };
317
318 let mut unsizing_params = DenseBitSet::new_empty(num_params);
319 for arg in tcx.type_of(tail_field.did).instantiate_identity().walk() {
320 if let Some(i) = maybe_unsizing_param_idx(arg) {
321 unsizing_params.insert(i);
322 }
323 }
324
325 for field in prefix_fields {
328 for arg in tcx.type_of(field.did).instantiate_identity().walk() {
329 if let Some(i) = maybe_unsizing_param_idx(arg) {
330 unsizing_params.remove(i);
331 }
332 }
333 }
334
335 unsizing_params
336}
337
338fn impl_self_is_guaranteed_unsized<'tcx>(tcx: TyCtxt<'tcx>, impl_def_id: DefId) -> bool {
339 debug_assert_eq!(tcx.def_kind(impl_def_id), DefKind::Impl { of_trait: true });
340
341 let infcx = tcx.infer_ctxt().ignoring_regions().build(ty::TypingMode::non_body_analysis());
342
343 let ocx = traits::ObligationCtxt::new(&infcx);
344 let cause = traits::ObligationCause::dummy();
345 let param_env = tcx.param_env(impl_def_id);
346
347 let tail = tcx.struct_tail_raw(
348 tcx.type_of(impl_def_id).instantiate_identity(),
349 |ty| {
350 ocx.structurally_normalize_ty(&cause, param_env, ty).unwrap_or_else(|_| {
351 Ty::new_error_with_message(
352 tcx,
353 tcx.def_span(impl_def_id),
354 "struct tail should be computable",
355 )
356 })
357 },
358 || (),
359 );
360
361 match tail.kind() {
362 ty::Dynamic(_, _, ty::Dyn) | ty::Slice(_) | ty::Str => true,
363 ty::Bool
364 | ty::Char
365 | ty::Int(_)
366 | ty::Uint(_)
367 | ty::Float(_)
368 | ty::Adt(_, _)
369 | ty::Foreign(_)
370 | ty::Array(_, _)
371 | ty::Pat(_, _)
372 | ty::RawPtr(_, _)
373 | ty::Ref(_, _, _)
374 | ty::FnDef(_, _)
375 | ty::FnPtr(_, _)
376 | ty::UnsafeBinder(_)
377 | ty::Closure(_, _)
378 | ty::CoroutineClosure(_, _)
379 | ty::Coroutine(_, _)
380 | ty::CoroutineWitness(_, _)
381 | ty::Never
382 | ty::Tuple(_)
383 | ty::Alias(_, _)
384 | ty::Param(_)
385 | ty::Bound(_, _)
386 | ty::Placeholder(_)
387 | ty::Infer(_)
388 | ty::Error(_) => false,
389 }
390}
391
392pub(crate) fn provide(providers: &mut Providers) {
393 *providers = Providers {
394 asyncness,
395 adt_sizedness_constraint,
396 param_env,
397 typing_env_normalized_for_post_analysis,
398 defaultness,
399 unsizing_params_for_adt,
400 impl_self_is_guaranteed_unsized,
401 ..*providers
402 };
403}