1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
use super::*;

use crate::abi_stability::ConstGeneric;

/////////////////////////////////////////////////////

/// The `repr(..)` attribute used on a type.
#[repr(u8)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, StableAbi)]
#[sabi(unsafe_sabi_opaque_fields)]
pub enum ReprAttr {
    /// This is an Option<NonZeroType>.
    /// In which the size and alignment of the Option<_> is exactly that of its contents.
    ///
    /// When translated to C,it is equivalent to the type parameter.
    OptionNonZero,
    /// This is an ffi-safe primitive type,declared in the compiler.
    Primitive,
    /// A struct whose fields are laid out like C,
    C,
    /// An enum with a `#[repr(C, IntegerType)]` attribute.
    CAndInt(DiscriminantRepr),
    /// A type with the same size,alignment and function ABI as
    /// its only non-zero-sized field.
    Transparent,
    /// Means that only `repr(IntegerType)` was used.
    Int(DiscriminantRepr),
    // Added just in case that I add support for it
    #[doc(hidden)]
    Packed {
        /// The alignment represented as a `1 << alignment_power_of_two`.
        alignment_power_of_two: u8,
    },
}

/////////////////////////////////////////////////////

/// A module path.
#[repr(transparent)]
#[derive(Debug, Copy, Clone, Eq, PartialEq, StableAbi)]
#[sabi(unsafe_sabi_opaque_fields)]
pub struct ModPath(NulStr<'static>);

impl ModPath {
    /// An item without a path
    pub const NO_PATH: Self = ModPath(nulstr_trunc!("<no path>"));

    /// An item in the prelude.
    pub const PRELUDE: Self = ModPath(nulstr_trunc!("<prelude>"));

    /// Constructs a ModPath from a string with a module path.
    pub const fn inside(path: NulStr<'static>) -> Self {
        ModPath(path)
    }
}

impl Display for ModPath {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Display::fmt(&self.0, f)
    }
}

/////////////////////////////////////////////////////

/// The compressed generic parameters of a type,
/// which can be expanded into a `GenericParams` by calling `expand`.
#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, StableAbi)]
#[sabi(unsafe_sabi_opaque_fields)]
pub struct CompGenericParams {
    /// The names of the lifetimes declared by a type.
    lifetime: NulStr<'static>,
    /// The type parameters of a type,getting them from the containing TypeLayout.
    types: StartLen,
    /// The const parameters of a type,getting them from the containing TypeLayout.
    consts: StartLen,
    lifetime_count: u8,
}

impl CompGenericParams {
    /// Constructs a CompGenericParams.
    pub const fn new(
        lifetime: NulStr<'static>,
        lifetime_count: u8,
        types: StartLen,
        consts: StartLen,
    ) -> Self {
        Self {
            lifetime,
            lifetime_count,
            types,
            consts,
        }
    }

    /// Expands this `CompGenericParams` into a `GenericParams`.
    pub fn expand(self, shared_vars: &'static SharedVars) -> GenericParams {
        GenericParams {
            lifetime: self.lifetime,
            types: &shared_vars.type_layouts()[self.types.to_range()],
            consts: &shared_vars.constants()[self.consts.to_range()],
            lifetime_count: self.lifetime_count,
        }
    }
}

/// The generic parameters of a type.
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct GenericParams {
    /// The names of the lifetimes declared by a type.
    pub(super) lifetime: NulStr<'static>,
    /// The type parameters of a type,getting them from the containing TypeLayout.
    pub(super) types: &'static [TypeLayoutCtor],
    /// The const parameters of a type,getting them from the containing TypeLayout.
    pub(super) consts: &'static [ConstGeneric],
    pub(super) lifetime_count: u8,
}

impl GenericParams {
    /// Whether this contains any generic parameters
    pub fn is_empty(&self) -> bool {
        self.lifetime.to_str().is_empty() && self.types.is_empty() && self.consts.is_empty()
    }

    /// Gets an iterator over the names of the lifetime parameters of the type.
    pub fn lifetimes(&self) -> impl Iterator<Item = &'static str> + Clone + Send + Sync + 'static {
        self.lifetime.to_str().split(',').filter(|x| !x.is_empty())
    }
    /// The amount of lifetimes of the type.
    pub fn lifetime_count(&self) -> usize {
        self.lifetime_count as usize
    }
    /// The type parameters of the type.
    pub fn type_params(&self) -> &'static [TypeLayoutCtor] {
        self.types
    }
    /// The const parameters of the type.
    pub fn const_params(&self) -> &'static [ConstGeneric] {
        self.consts
    }
}

impl Display for GenericParams {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt("<", f)?;

        let post_iter = |i: usize, len: usize, f: &mut Formatter<'_>| -> fmt::Result {
            if i + 1 < len {
                fmt::Display::fmt(", ", f)?;
            }
            Ok(())
        };

        for (i, param) in self.lifetimes().enumerate() {
            fmt::Display::fmt(param, &mut *f)?;
            post_iter(i, self.lifetime_count(), &mut *f)?;
        }
        for (i, param) in self.types.iter().cloned().enumerate() {
            fmt::Debug::fmt(&param.get().full_type(), &mut *f)?;
            post_iter(i, self.types.len(), &mut *f)?;
        }
        for (i, param) in self.consts.iter().enumerate() {
            fmt::Debug::fmt(param, &mut *f)?;
            post_iter(i, self.consts.len(), &mut *f)?;
        }
        fmt::Display::fmt(">", f)?;
        Ok(())
    }
}

///////////////////////////////////////////////////////////////////////////////

/// Types defined in the compiler
#[repr(u8)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, StableAbi)]
#[sabi(unsafe_sabi_opaque_fields)]
pub enum TLPrimitive {
    U8,
    I8,
    U16,
    I16,
    U32,
    I32,
    U64,
    I64,
    Usize,
    Isize,
    Bool,
    /// A `&T`
    SharedRef,
    /// A `&mut T`
    MutRef,
    /// A `*const T`
    ConstPtr,
    /// A `*mut T`
    MutPtr,
    /// An array.
    Array {
        len: usize,
    },
}

///////////////////////////

/// The typename and generics of the type this layout is associated to,
/// used for printing types (eg: `RVec<u8>` ).
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct FmtFullType {
    pub(super) name: &'static str,
    pub(super) generics: GenericParams,
    pub(super) primitive: Option<TLPrimitive>,
    pub(super) utypeid: UTypeId,
}

impl FmtFullType {
    /// The name of a type.
    pub fn name(&self) -> &'static str {
        self.name
    }
    /// The generic parmaters of a type.
    pub fn generics(&self) -> GenericParams {
        self.generics
    }
}

////////////////////////////////////

/// Either a TLField or a TLFunction.
#[repr(u8)]
#[derive(Copy, Clone, Debug, Eq, PartialEq, StableAbi)]
#[sabi(unsafe_sabi_opaque_fields)]
pub enum TLFieldOrFunction {
    Field(TLField),
    Function(TLFunction),
}

impl From<TLField> for TLFieldOrFunction {
    fn from(x: TLField) -> Self {
        TLFieldOrFunction::Field(x)
    }
}

impl From<TLFunction> for TLFieldOrFunction {
    fn from(x: TLFunction) -> Self {
        TLFieldOrFunction::Function(x)
    }
}

impl Display for TLFieldOrFunction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TLFieldOrFunction::Field(x) => Display::fmt(x, f),
            TLFieldOrFunction::Function(x) => Display::fmt(x, f),
        }
    }
}

impl TLFieldOrFunction {
    /// Outputs this into a String with `Display` formatting.
    pub fn formatted_layout(&self) -> String {
        match self {
            TLFieldOrFunction::Field(x) => x.layout().to_string(),
            TLFieldOrFunction::Function(x) => x.to_string(),
        }
    }
}

//////////////////////////////////////////////////////////////////////////////