Skip to main content

charon_driver/frontend/types/
ty.rs

1//! Frontend representations of Rust types and related type operations.
2
3use 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/// Reflects [`rustc_middle::ty::Ty`]
16#[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    /// If this type represents something that implements the `Fn*` traits, return the
33    /// corresponding item.
34    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/// Reflects [`ty::TyKind`]
59#[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                // Note: loss of precision, we erase the bound vars.
103                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    /// Points to a synthetic item used to build impls for function pointer types.
205    pub item: ItemRef<'tcx>,
206}
207
208/// Reflects [`ty::ClosureArgs`]
209#[derive(Debug, Clone, PartialEq, Eq, Hash)]
210pub struct ClosureTy<'tcx> {
211    pub item: ItemRef<'tcx>,
212}
213
214impl<'tcx> ClosureTy<'tcx> {
215    /// The base kind of this closure. The kinds are ordered by inclusion: any `Fn` works as an
216    /// `FnMut`, and any `FnMut` works as an `FnOnce`.
217    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    /// The signature of the function that this closure implements, e.g. `fn(A, B, C) -> D`.
223    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    // Manual implementation because we need the `def_id` of the closure.
230    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    /// The `Sized` proof for the element type, if we're not hiding `Sized`.
257    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    /// The `Sized` proof for the element type, if we're not hiding `Sized`.
280    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    /// The principal trait clause, if any.
320    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/// Reflects [`ty::UserSelfTy`]
336#[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/// Reflects [`ty::UserArgs`]
344#[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/// Reflects [`ty::UserType`]: this is currently
352/// disabled, and everything is printed as debug in the
353/// [`UserType::Todo`] variant.
354#[derive(Debug, Clone, AdtInto)]
355#[args(<'tcx, S: UnderOwnerState<'tcx>>, from: ty::UserType<'tcx>, state: S as _s)]
356pub enum UserType {
357    // TODO: for now, we don't use user types at all.
358    // We disable it for now, since it cause the following to fail:
359    //
360    //    pub const MY_VAL: u16 = 5;
361    //    pub type Alias = MyStruct<MY_VAL>; // Using the literal 5, it goes through
362    //
363    //    pub struct MyStruct<const VAL: u16> {}
364    //
365    //    impl<const VAL: u16> MyStruct<VAL> {
366    //        pub const MY_CONST: u16 = VAL;
367    //    }
368    //
369    //    pub fn do_something() -> u32 {
370    //        u32::from(Alias::MY_CONST)
371    //    }
372    //
373    // In this case, we get a [ty::ConstKind::Bound] in
374    // [do_something], which we are not able to translate.
375    // See: https://github.com/hacspec/hax/pull/209
376
377    // Ty(Ty),
378    // TypeOf(DefId, UserArgs),
379    #[todo]
380    Todo(String),
381}
382
383/// Reflects [`ty::TypeAndMut`]
384#[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/// This type merges the information from
399/// [`ty::AliasTyKind`] and [`ty::AliasTy`].
400#[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/// Reflects [`rustc_middle::ty::AliasTyKind`].
408#[derive(Debug, Clone, PartialEq, Eq, Hash)]
409pub enum AliasKind<'tcx> {
410    /// The projection of a trait type: `<Ty as Trait<...>>::Type<...>`
411    Projection(ItemRef<'tcx>),
412    /// An associated type in an inherent impl.
413    Inherent,
414    /// An `impl Trait` opaque type.
415    Opaque {
416        /// The real type hidden inside this opaque type.
417        hidden_ty: Ty<'tcx>,
418    },
419    /// A type alias that references opaque types. Likely to always be normalized away.
420    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        // Try to normalize the alias first.
440        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                // Reveal the underlying `impl Trait` type.
454                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/// Reflects [`ty::CanonicalUserTypeAnnotation`]
488#[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/// The metadata to attach to the newly-unsized ptr.
498#[derive(Debug, Clone, PartialEq, Eq, Hash)]
499pub enum UnsizingMetadata<'tcx> {
500    /// Unsize an array to a slice, storing the length as metadata.
501    Length(ConstantExpr<'tcx>),
502    /// Unsize a non-dyn type to a dyn type, adding a vtable pointer as metadata.
503    DirectVTable(TraitProof<'tcx>),
504    /// Unsize a dyn-type to another dyn-type, (optionally) indexing within the current vtable.
505    NestedVTable(DynBinder<'tcx, TraitProof<'tcx>>),
506    /// Generic case: proof of `Unsize` between the pointees.
507    UnsizeClause(TraitProof<'tcx>),
508    /// Generic case: proof of `CoerceUnsized` between the struct fields.
509    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    // Unless boxes are built-in, we go through their fields like for other smart pointers.
519    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        // Like `rustc_monomorphize::custom_coerce_unsize_info`: for a `CoerceUnsized` struct
526        // (e.g. `Rc`), find the impl and recurse into the field it coerces.
527        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/// Reflects [`ty::FnSig`]
606#[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
622/// Reflects [`ty::PolyFnSig`]
623pub type PolyFnSig<'tcx> = Binder<TyFnSig<'tcx>>;
624
625/// Retrieve a closure's signature.
626pub 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/// Reflects [`ty::ClosureKind`]
634#[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}