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