1use super::predicates::resolve_for_dyn;
4
5use crate::frontend::prelude::*;
6
7use rustc_data_structures::intern::Interned;
8use rustc_middle::ty;
9use rustc_middle::ty::inherent::IntoKind;
10use rustc_span::DUMMY_SP;
11use rustc_span::def_id::DefId as RDefId;
12
13sinto_reexport!(rustc_abi::ExternAbi, ty::IntTy, ty::UintTy, ty::FloatTy);
14
15#[derive(Debug, Clone, PartialEq, Eq, Hash)]
17pub struct Ty<'tcx> {
18 pub(crate) kind: Interned<'tcx, TyKind<'tcx>>,
19}
20
21impl<'tcx> Ty<'tcx> {
22 pub fn new<S: BaseState<'tcx>>(s: &S, kind: TyKind<'tcx>) -> Self {
23 Ty {
24 kind: s.base().ty_interner.intern(kind),
25 }
26 }
27
28 pub fn kind(&self) -> &TyKind<'tcx> {
29 &self.kind
30 }
31
32 pub fn callable_item(&self) -> Option<&ItemRef<'tcx>> {
35 match self.kind() {
36 TyKind::Closure(closure) => Some(&closure.item),
37 TyKind::FnDef(fn_def) => Some(&fn_def.item),
38 TyKind::FnPtr(fn_ptr) => Some(&fn_ptr.item),
39 _ => None,
40 }
41 }
42}
43
44impl<'tcx, S: UnderOwnerState<'tcx>> SInto<S, Ty<'tcx>> for rustc_middle::ty::Ty<'tcx> {
45 fn sinto(&self, s: &S) -> Ty<'tcx> {
46 if let Some(ty) = s.with_cache(|cache| cache.tys.get(self).cloned()) {
47 return ty;
48 }
49 let kind: TyKind<'tcx> = self.kind().sinto(s);
50 let ty = Ty::new(s, kind);
51 s.with_cache(|cache| {
52 cache.tys.insert(*self, ty.clone());
53 });
54 ty
55 }
56}
57
58#[derive(Debug, Clone, PartialEq, Eq, Hash)]
60pub enum TyKind<'tcx> {
61 Bool,
62 Char,
63 Int(IntTy),
64 Uint(UintTy),
65 Float(FloatTy),
66 FnDef(FnDefTy<'tcx>),
67 FnPtr(FnPtrTy<'tcx>),
68 Closure(ClosureTy<'tcx>),
69 Adt(AdtTy<'tcx>),
70 Foreign(ForeignTy<'tcx>),
71 Array(ArrayTy<'tcx>),
72 Pat(PatTy<'tcx>),
73 Slice(SliceTy<'tcx>),
74 Tuple(TupleTy<'tcx>),
75 Str(StrTy<'tcx>),
76 RawPtr(RawPtrTy<'tcx>),
77 Ref(RefTy<'tcx>),
78 DynTrait(DynTraitTy<'tcx>),
79 Coroutine(CoroutineTy<'tcx>),
80 Never,
81 Alias(Alias<'tcx>),
82 Param(ParamTy),
83 Bound(BoundTyRef),
84 Placeholder(PlaceholderTy),
85 Infer(InferTy),
86 Error,
87 Todo(String),
88}
89
90impl<'tcx, S: UnderOwnerState<'tcx>> SInto<S, TyKind<'tcx>> for ty::TyKind<'tcx> {
91 #[tracing::instrument(level = "trace", skip(s))]
92 fn sinto(&self, s: &S) -> TyKind<'tcx> {
93 let base = s.base();
94 let tcx = base.tcx;
95 match self {
96 Self::Bool => TyKind::Bool,
97 Self::Char => TyKind::Char,
98 Self::Int(int_ty) => TyKind::Int(int_ty.sinto(s)),
99 Self::Uint(uint_ty) => TyKind::Uint(uint_ty.sinto(s)),
100 Self::Float(float_ty) => TyKind::Float(float_ty.sinto(s)),
101 Self::FnDef(fun_id, generics) => {
102 let generics = tcx.instantiate_bound_regions_with_erased(*generics);
104 TyKind::FnDef(FnDefTy {
105 item: translate_item_ref(s, *fun_id, generics),
106 })
107 }
108 Self::FnPtr(tys, header) => {
109 let sig = tys.with(*header);
110 let item = ItemRef::translate_fn_ptr(s, sig);
111 TyKind::FnPtr(FnPtrTy {
112 sig: Box::new(sig.sinto(s)),
113 item,
114 })
115 }
116 Self::Closure(def_id, generics) => {
117 TyKind::Closure(ClosureTy::sfrom(s, *def_id, *generics))
118 }
119 Self::Adt(adt_def, generics) => TyKind::Adt(AdtTy {
120 item: translate_item_ref(s, adt_def.did(), *generics),
121 }),
122 Self::Foreign(def_id) => TyKind::Foreign(ForeignTy {
123 item: translate_item_ref(s, *def_id, Default::default()),
124 }),
125 Self::Array(ty, len) => {
126 let args = tcx.mk_args(&[(*ty).into(), (*len).into()]);
127 let sized_trait = tcx.lang_items().sized_trait().unwrap();
128 TyKind::Array(ArrayTy {
129 item: ItemRef::translate_synthetic(s, SyntheticItem::Array, args),
130 has_sized_proof: !base
131 .elab_ctx
132 .bounds_options()
133 .remove_traits
134 .contains(&sized_trait),
135 })
136 }
137 Self::Pat(ty, pat) => TyKind::Pat(PatTy {
138 ty: ty.sinto(s),
139 pat: pat.sinto(s),
140 }),
141 Self::Slice(ty) => {
142 let args = tcx.mk_args(&[(*ty).into()]);
143 let sized_trait = tcx.lang_items().sized_trait().unwrap();
144 TyKind::Slice(SliceTy {
145 item: ItemRef::translate_synthetic(s, SyntheticItem::Slice, args),
146 has_sized_proof: !base
147 .elab_ctx
148 .bounds_options()
149 .remove_traits
150 .contains(&sized_trait),
151 })
152 }
153 Self::Tuple(tys) => {
154 let args = tcx.mk_args_from_iter(tys.into_iter().map(ty::GenericArg::from));
155 TyKind::Tuple(TupleTy {
156 item: ItemRef::translate_synthetic(s, SyntheticItem::Tuple(tys.len()), args),
157 })
158 }
159 Self::Str => {
160 let args = tcx.mk_args(&[]);
161 TyKind::Str(StrTy {
162 item: ItemRef::translate_synthetic(s, SyntheticItem::Str, args),
163 })
164 }
165 Self::RawPtr(ty, mutbl) => TyKind::RawPtr(RawPtrTy {
166 ty: ty.sinto(s),
167 mutbl: mutbl.sinto(s),
168 }),
169 Self::Ref(region, ty, mutbl) => TyKind::Ref(RefTy {
170 region: region.sinto(s),
171 ty: ty.sinto(s),
172 mutbl: mutbl.sinto(s),
173 }),
174 Self::Dynamic(preds, region) => TyKind::DynTrait(DynTraitTy {
175 binder: resolve_for_dyn(s, preds, |_, _| ()),
176 region: region.sinto(s),
177 }),
178 Self::Coroutine(def_id, generics) => TyKind::Coroutine(CoroutineTy {
179 item: translate_item_ref(s, *def_id, *generics),
180 }),
181 Self::Never => TyKind::Never,
182 Self::Alias(_, alias_ty) => Alias::from(s, alias_ty),
183 Self::Param(param) => TyKind::Param(param.sinto(s)),
184 Self::Bound(index, ty) => TyKind::Bound(BoundTyRef {
185 index: index.sinto(s),
186 ty: ty.sinto(s),
187 }),
188 Self::Placeholder(placeholder) => TyKind::Placeholder(placeholder.sinto(s)),
189 Self::Infer(infer) => TyKind::Infer(infer.sinto(s)),
190 Self::Error(..) => TyKind::Error,
191 other => TyKind::Todo(format!("{other:?}")),
192 }
193 }
194}
195
196#[derive(Debug, Clone, PartialEq, Eq, Hash)]
197pub struct FnDefTy<'tcx> {
198 pub item: ItemRef<'tcx>,
199}
200
201#[derive(Debug, Clone, PartialEq, Eq, Hash)]
202pub struct FnPtrTy<'tcx> {
203 pub sig: Box<PolyFnSig<'tcx>>,
204 pub item: ItemRef<'tcx>,
206}
207
208#[derive(Debug, Clone, PartialEq, Eq, Hash)]
210pub struct ClosureTy<'tcx> {
211 pub item: ItemRef<'tcx>,
212}
213
214impl<'tcx> ClosureTy<'tcx> {
215 pub fn kind(&self, s: &impl BaseState<'tcx>) -> ClosureKind {
218 let s = &s.with_frontend_owner(&self.item.def_id);
219 self.item.rustc_args(s).as_closure().kind().sinto(s)
220 }
221
222 pub fn fn_sig(&self, s: &impl BaseState<'tcx>) -> PolyFnSig<'tcx> {
224 let s = &s.with_frontend_owner(&self.item.def_id);
225 let args = self.item.rustc_args(s);
226 closure_sig(s.tcx(), args.as_closure()).sinto(s)
227 }
228
229 pub fn sfrom<S>(s: &S, def_id: RDefId, from: ty::GenericArgs<'tcx>) -> Self
231 where
232 S: UnderOwnerState<'tcx>,
233 {
234 let item = translate_item_ref(s, def_id, from);
235 ClosureTy { item }
236 }
237}
238
239#[derive(Debug, Clone, PartialEq, Eq, Hash)]
240pub struct AdtTy<'tcx> {
241 pub item: ItemRef<'tcx>,
242}
243
244#[derive(Debug, Clone, PartialEq, Eq, Hash)]
245pub struct ForeignTy<'tcx> {
246 pub item: ItemRef<'tcx>,
247}
248
249#[derive(Debug, Clone, PartialEq, Eq, Hash)]
250pub struct ArrayTy<'tcx> {
251 pub item: ItemRef<'tcx>,
252 has_sized_proof: bool,
253}
254
255impl<'tcx> ArrayTy<'tcx> {
256 pub fn element_sized_proof(&self) -> Option<&TraitProof<'tcx>> {
258 if self.has_sized_proof {
259 Some(&self.item.trait_proofs[0])
260 } else {
261 None
262 }
263 }
264}
265
266#[derive(Debug, Clone, PartialEq, Eq, Hash)]
267pub struct PatTy<'tcx> {
268 pub ty: Ty<'tcx>,
269 pub pat: Pattern<'tcx>,
270}
271
272#[derive(Debug, Clone, PartialEq, Eq, Hash)]
273pub struct SliceTy<'tcx> {
274 pub item: ItemRef<'tcx>,
275 has_sized_proof: bool,
276}
277
278impl<'tcx> SliceTy<'tcx> {
279 pub fn element_sized_proof(&self) -> Option<&TraitProof<'tcx>> {
281 if self.has_sized_proof {
282 Some(&self.item.trait_proofs[0])
283 } else {
284 None
285 }
286 }
287}
288
289#[derive(Debug, Clone, PartialEq, Eq, Hash)]
290pub struct TupleTy<'tcx> {
291 pub item: ItemRef<'tcx>,
292}
293
294#[derive(Debug, Clone, PartialEq, Eq, Hash)]
295pub struct StrTy<'tcx> {
296 pub item: ItemRef<'tcx>,
297}
298
299#[derive(Debug, Clone, PartialEq, Eq, Hash)]
300pub struct RawPtrTy<'tcx> {
301 pub ty: Ty<'tcx>,
302 pub mutbl: Mutability,
303}
304
305#[derive(Debug, Clone, PartialEq, Eq, Hash)]
306pub struct RefTy<'tcx> {
307 pub region: Region<'tcx>,
308 pub ty: Ty<'tcx>,
309 pub mutbl: Mutability,
310}
311
312#[derive(Debug, Clone, PartialEq, Eq, Hash)]
313pub struct DynTraitTy<'tcx> {
314 pub binder: DynBinder<'tcx, ()>,
315 pub region: Region<'tcx>,
316}
317
318impl<'tcx> DynTraitTy<'tcx> {
319 pub fn principal_trait_clause(&self) -> Option<&Binder<ClauseKind<'tcx>>> {
321 let clause = &self.binder.predicates.predicates.first()?.clause.kind;
322 if matches!(clause.frontend_skip_binder_ref(), ClauseKind::Trait(_)) {
323 Some(clause)
324 } else {
325 None
326 }
327 }
328}
329
330#[derive(Debug, Clone, PartialEq, Eq, Hash)]
331pub struct CoroutineTy<'tcx> {
332 pub item: ItemRef<'tcx>,
333}
334
335#[derive(Debug, Clone, AdtInto)]
337#[args(< S: UnderOwnerState<'tcx>>, from: ty::UserSelfTy<'tcx>, state: S as gstate)]
338pub struct UserSelfTy<'tcx> {
339 pub impl_def_id: DefId,
340 pub self_ty: Ty<'tcx>,
341}
342
343#[derive(Debug, Clone, AdtInto)]
345#[args(< S: UnderOwnerState<'tcx>>, from: ty::UserArgs<'tcx>, state: S as gstate)]
346pub struct UserArgs<'tcx> {
347 pub args: Vec<GenericArg<'tcx>>,
348 pub user_self_ty: Option<UserSelfTy<'tcx>>,
349}
350
351#[derive(Debug, Clone, AdtInto)]
355#[args(<'tcx, S: UnderOwnerState<'tcx>>, from: ty::UserType<'tcx>, state: S as _s)]
356pub enum UserType {
357 #[todo]
380 Todo(String),
381}
382
383#[derive(AdtInto)]
385#[args(< S: UnderOwnerState<'tcx>>, from: ty::TypeAndMut<'tcx>, state: S as gstate)]
386#[derive(Debug, Clone, PartialEq, Eq, Hash)]
387pub struct TypeAndMut<'tcx> {
388 pub ty: Ty<'tcx>,
389 pub mutbl: Mutability,
390}
391
392impl<S, U, T: SInto<S, U>> SInto<S, Vec<U>> for ty::List<T> {
393 fn sinto(&self, s: &S) -> Vec<U> {
394 self.iter().map(|x| x.sinto(s)).collect()
395 }
396}
397
398#[derive(Debug, Clone, PartialEq, Eq, Hash)]
401pub struct Alias<'tcx> {
402 pub kind: AliasKind<'tcx>,
403 pub args: Vec<GenericArg<'tcx>>,
404 pub def_id: DefId,
405}
406
407#[derive(Debug, Clone, PartialEq, Eq, Hash)]
409pub enum AliasKind<'tcx> {
410 Projection(ItemRef<'tcx>),
412 Inherent,
414 Opaque {
416 hidden_ty: Ty<'tcx>,
418 },
419 Free,
421}
422
423pub fn alias_ty_kind_def_id<'tcx>(kind: ty::AliasTyKind<'tcx>) -> RDefId {
424 match kind {
425 ty::AliasTyKind::Projection { def_id }
426 | ty::AliasTyKind::Inherent { def_id }
427 | ty::AliasTyKind::Opaque { def_id }
428 | ty::AliasTyKind::Free { def_id } => def_id,
429 }
430}
431
432impl<'tcx> Alias<'tcx> {
433 #[tracing::instrument(level = "trace", skip(s))]
434 fn from<S: UnderOwnerState<'tcx>>(s: &S, alias_ty: &ty::AliasTy<'tcx>) -> TyKind<'tcx> {
435 let tcx = s.base().tcx;
436 let typing_env = s.typing_env();
437 use ty::AliasTyKind as RustAliasKind;
438
439 let ty = ty::Ty::new_alias(tcx, ty::IsRigid::No, *alias_ty);
441 let ty = normalize(tcx, typing_env, ty::Unnormalized::new(ty));
442 let ty::Alias(_is_rigid, alias_ty) = ty.kind() else {
443 let ty: Ty = ty.sinto(s);
444 return ty.kind().clone();
445 };
446
447 let kind = match alias_ty.kind {
448 RustAliasKind::Projection { def_id } => {
449 AliasKind::Projection(ItemRef::translate_projection(s, def_id, alias_ty.args))
450 }
451 RustAliasKind::Inherent { .. } => AliasKind::Inherent,
452 RustAliasKind::Opaque { def_id } => {
453 let ty = tcx.type_of(def_id).instantiate(tcx, alias_ty.args);
455 let ty = normalize(tcx, s.typing_env(), ty);
456 AliasKind::Opaque {
457 hidden_ty: ty.sinto(s),
458 }
459 }
460 RustAliasKind::Free { .. } => AliasKind::Free,
461 };
462 TyKind::Alias(Alias {
463 kind,
464 args: alias_ty.args.sinto(s),
465 def_id: alias_ty_kind_def_id(alias_ty.kind).sinto(s),
466 })
467 }
468}
469
470#[derive(AdtInto)]
471#[args(< S: UnderOwnerState<'tcx>>, from: ty::pattern::PatternKind<'tcx>, state: S as gstate)]
472#[derive(Debug, Clone, PartialEq, Eq, Hash)]
473pub enum Pattern<'tcx> {
474 Range {
475 start: ConstantExpr<'tcx>,
476 end: ConstantExpr<'tcx>,
477 },
478 Or(Vec<Pattern<'tcx>>),
479 NotNull,
480}
481
482impl<'tcx, S: UnderOwnerState<'tcx>> SInto<S, Pattern<'tcx>> for ty::Pattern<'tcx> {
483 fn sinto(&self, s: &S) -> Pattern<'tcx> {
484 self.kind().sinto(s)
485 }
486}
487#[derive(AdtInto)]
489#[args(< S: UnderOwnerState<'tcx>>, from: ty::CanonicalUserTypeAnnotation<'tcx>, state: S as gstate)]
490#[derive(Debug, Clone)]
491pub struct CanonicalUserTypeAnnotation<'tcx> {
492 pub user_ty: CanonicalUserType,
493 pub span: Span,
494 pub inferred_ty: Ty<'tcx>,
495}
496
497#[derive(Debug, Clone, PartialEq, Eq, Hash)]
499pub enum UnsizingMetadata<'tcx> {
500 Length(ConstantExpr<'tcx>),
502 DirectVTable(TraitProof<'tcx>),
504 NestedVTable(DynBinder<'tcx, TraitProof<'tcx>>),
506 UnsizeClause(TraitProof<'tcx>),
508 CoerceUnsizedClause(TraitProof<'tcx>),
510}
511
512pub fn compute_unsizing_metadata<'tcx, S: UnderOwnerState<'tcx>>(
513 s: &S,
514 src_ty: ty::Ty<'tcx>,
515 tgt_ty: ty::Ty<'tcx>,
516) -> (Vec<FieldIdx>, UnsizingMetadata<'tcx>) {
517 let tcx = s.base().tcx;
518 let builtin_deref = |ty: ty::Ty<'tcx>| {
520 (!ty.is_box() || s.base().options.treat_box_as_builtin)
521 .then(|| ty.builtin_deref(true))
522 .flatten()
523 };
524 let (Some(src_ty), Some(tgt_ty)) = (builtin_deref(src_ty), builtin_deref(tgt_ty)) else {
525 return match (src_ty.kind(), tgt_ty.kind()) {
528 (ty::Adt(def, src_args), ty::Adt(_, tgt_args)) => {
529 let coerce_trait = tcx.lang_items().coerce_unsized_trait().unwrap();
530 let tref = ty::TraitRef::new(tcx, coerce_trait, [src_ty, tgt_ty]);
531 let proof =
532 s.with_predicate_searcher(|ps, ctx| ps.resolve(ctx, &ty::Binder::dummy(tref)));
533 let elaboration::TraitProofKind::Concrete(impl_ref) = &proof.contents().kind else {
534 unreachable!("`CoerceUnsized` between ADTs is always proven by a concrete impl")
535 };
536 let info = tcx
537 .coerce_unsized_info(impl_ref.def_id.real_rust_def_id())
538 .unwrap();
539 let ty::adjustment::CustomCoerceUnsized::Struct(i) = info.custom_kind.unwrap();
540 let field = &def.non_enum_variant().fields[i];
541 let typing_env = s.typing_env();
542 let src_ty = normalize(tcx, typing_env, field.ty(tcx, *src_args));
543 let tgt_ty = normalize(tcx, typing_env, field.ty(tcx, *tgt_args));
544 let (mut path, meta) = compute_unsizing_metadata(s, src_ty, tgt_ty);
545 path.insert(0, i);
546 (path, meta)
547 }
548 (ty::Pat(a, _), ty::Pat(b, _)) => compute_unsizing_metadata(s, *a, *b),
549 _ => {
550 let coerce_trait =
551 tcx.require_lang_item(rustc_attr_ir::LangItem::CoerceUnsized, DUMMY_SP);
552 let tref = ty::TraitRef::new(tcx, coerce_trait, [src_ty, tgt_ty]);
553 let proof = solve_trait(s, ty::Binder::dummy(tref));
554 (vec![], UnsizingMetadata::CoerceUnsizedClause(proof))
555 }
556 };
557 };
558 let typing_env = s.typing_env();
559 let (src_ty, tgt_ty) =
560 tcx.struct_lockstep_tails_raw(src_ty, tgt_ty, |ty| normalize(tcx, typing_env, ty));
561
562 let meta = match (&src_ty.kind(), &tgt_ty.kind()) {
563 (ty::Array(_, len), ty::Slice(_) | ty::Str) => {
564 let len = len.sinto(s);
565 UnsizingMetadata::Length(len)
566 }
567 (ty::Dynamic(from_preds, _), ty::Dynamic(to_preds, ..)) => {
568 let trait_proof = resolve_for_dyn(s, from_preds, |searcher, fresh_ty| {
569 let to_pred = if let Some(to_principal) = to_preds.principal() {
570 to_principal.with_self_ty(tcx, fresh_ty)
571 } else {
572 let def_id = to_preds
573 .iter()
574 .find_map(|pred| match pred.skip_binder() {
575 ty::ExistentialPredicate::AutoTrait(def_id) => Some(def_id),
576 _ => None,
577 })
578 .expect("expected a trait predicate in dyn upcast target");
579 ty::Binder::dummy(ty::TraitRef::new(tcx, def_id, [fresh_ty]))
580 };
581 searcher.resolve(&s.base_state(), &to_pred)
582 });
583 UnsizingMetadata::NestedVTable(trait_proof)
584 }
585 (_, ty::Dynamic(preds, ..)) => {
586 let pred = preds[0].with_self_ty(tcx, src_ty);
587 let clause = pred.as_trait_clause().expect(
588 "the first `ExistentialPredicate` of `TyKind::Dynamic` \\
589 should be a trait clause",
590 );
591 let tref = clause.rebind(clause.skip_binder().trait_ref);
592 let trait_proof = solve_trait(s, tref);
593
594 UnsizingMetadata::DirectVTable(trait_proof)
595 }
596 _ => {
597 let unsize_trait = tcx.require_lang_item(rustc_attr_ir::LangItem::Unsize, DUMMY_SP);
598 let tref = ty::TraitRef::new(tcx, unsize_trait, [src_ty, tgt_ty]);
599 UnsizingMetadata::UnsizeClause(solve_trait(s, ty::Binder::dummy(tref)))
600 }
601 };
602 (vec![], meta)
603}
604
605#[derive(Debug, Clone, PartialEq, Eq, Hash)]
607#[derive(AdtInto)]
608#[args(< S: UnderOwnerState<'tcx>>, from: ty::FnSig<'tcx>, state: S as s)]
609pub struct TyFnSig<'tcx> {
610 #[value(self.inputs().sinto(s))]
611 pub inputs: Vec<Ty<'tcx>>,
612 #[value(self.output().sinto(s))]
613 pub output: Ty<'tcx>,
614 #[value(self.c_variadic())]
615 pub c_variadic: bool,
616 #[value(self.safety())]
617 pub safety: Safety,
618 #[value(self.abi())]
619 pub abi: ExternAbi,
620}
621
622pub type PolyFnSig<'tcx> = Binder<TyFnSig<'tcx>>;
624
625pub fn closure_sig<'tcx>(
627 tcx: ty::TyCtxt<'tcx>,
628 closure: ty::ClosureArgs<ty::TyCtxt<'tcx>>,
629) -> ty::PolyFnSig<'tcx> {
630 tcx.signature_unclosure(closure.sig(), rustc_hir::Safety::Safe)
631}
632
633#[derive(AdtInto)]
635#[args(<'tcx, S: UnderOwnerState<'tcx>>, from: ty::ClosureKind, state: S as _tcx)]
636#[derive(Debug, Clone, PartialEq, Eq, Hash)]
637pub enum ClosureKind {
638 Fn,
639 FnMut,
640 FnOnce,
641}