core/mem/
type_info.rs

1//! MVP for exposing compile-time information about types in a
2//! runtime or const-eval processable way.
3
4use crate::any::TypeId;
5use crate::intrinsics::type_of;
6
7/// Compile-time type information.
8#[derive(Debug)]
9#[non_exhaustive]
10#[lang = "type_info"]
11#[unstable(feature = "type_info", issue = "146922")]
12pub struct Type {
13    /// Per-type information
14    pub kind: TypeKind,
15    /// Size of the type. `None` if it is unsized
16    pub size: Option<usize>,
17}
18
19impl TypeId {
20    /// Compute the type information of a concrete type.
21    /// It can only be called at compile time.
22    #[unstable(feature = "type_info", issue = "146922")]
23    #[rustc_const_unstable(feature = "type_info", issue = "146922")]
24    pub const fn info(self) -> Type {
25        type_of(self)
26    }
27}
28
29impl Type {
30    /// Returns the type information of the generic type parameter.
31    #[unstable(feature = "type_info", issue = "146922")]
32    #[rustc_const_unstable(feature = "type_info", issue = "146922")]
33    // FIXME(reflection): don't require the 'static bound
34    pub const fn of<T: 'static>() -> Self {
35        const { TypeId::of::<T>().info() }
36    }
37}
38
39/// Compile-time type information.
40#[derive(Debug)]
41#[non_exhaustive]
42#[unstable(feature = "type_info", issue = "146922")]
43pub enum TypeKind {
44    /// Tuples.
45    Tuple(Tuple),
46    /// Primitives
47    /// FIXME(#146922): disambiguate further
48    Leaf,
49    /// FIXME(#146922): add all the common types
50    Other,
51}
52
53/// Compile-time type information about tuples.
54#[derive(Debug)]
55#[non_exhaustive]
56#[unstable(feature = "type_info", issue = "146922")]
57pub struct Tuple {
58    /// All fields of a tuple.
59    pub fields: &'static [Field],
60}
61
62/// Compile-time type information about fields of tuples, structs and enum variants.
63#[derive(Debug)]
64#[non_exhaustive]
65#[unstable(feature = "type_info", issue = "146922")]
66pub struct Field {
67    /// The field's type.
68    pub ty: TypeId,
69    /// Offset in bytes from the parent type
70    pub offset: usize,
71}