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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
use super::*;

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

/// The parts of TLData that don't change based on generic parameters.
#[repr(u8)]
#[derive(Copy, Clone, StableAbi)]
#[sabi(unsafe_sabi_opaque_fields)]
pub enum MonoTLData {
    ///
    Primitive(TLPrimitive),
    /// A type that's only compared for size and alignment.
    Opaque,
    ///
    Struct {
        ///
        fields: CompTLFields,
    },
    ///
    Union {
        ///
        fields: CompTLFields,
    },
    ///
    Enum(MonoTLEnum),
    ///
    PrefixType(MonoTLPrefixType),
}

impl MonoTLData {
    /// Teh `MonoTLData` for an empty struct.
    pub const EMPTY: Self = MonoTLData::Struct {
        fields: CompTLFields::EMPTY,
    };

    /// Constructs `MonoTLData::Struct` from a slice of its fields.
    pub const fn struct_(fields: RSlice<'static, CompTLField>) -> Self {
        MonoTLData::Struct {
            fields: CompTLFields::from_fields(fields),
        }
    }

    #[doc(hidden)]
    pub const fn derive_struct(fields: CompTLFields) -> Self {
        MonoTLData::Struct { fields }
    }

    /// Constructs `MonoTLData::Union` from a slice of its fields.
    pub const fn union_(fields: RSlice<'static, CompTLField>) -> Self {
        MonoTLData::Union {
            fields: CompTLFields::from_fields(fields),
        }
    }

    #[doc(hidden)]
    pub const fn derive_union(fields: CompTLFields) -> Self {
        MonoTLData::Union { fields }
    }

    /// Constructs a `MonoTLData::PrefixType`
    pub const fn prefix_type(
        first_suffix_field: usize,
        conditional_prefix_fields: FieldConditionality,
        fields: RSlice<'static, CompTLField>,
    ) -> Self {
        MonoTLData::PrefixType(MonoTLPrefixType {
            first_suffix_field: first_suffix_field as u8,
            conditional_prefix_fields,
            fields: CompTLFields::from_fields(fields),
        })
    }

    /// Constructs `MonoTLData::Struct` from a slice of its fields.
    pub const fn struct_derive(fields: CompTLFields) -> Self {
        MonoTLData::Struct { fields }
    }

    /// Constructs `MonoTLData::Union` from a slice of its fields.
    pub const fn union_derive(fields: CompTLFields) -> Self {
        MonoTLData::Union { fields }
    }

    /// Constructs a `MonoTLData::PrefixType`
    pub const fn prefix_type_derive(
        first_suffix_field: usize,
        conditional_prefix_fields: u64,
        fields: CompTLFields,
    ) -> Self {
        MonoTLData::PrefixType(MonoTLPrefixType {
            first_suffix_field: first_suffix_field as u8,
            conditional_prefix_fields: FieldConditionality::from_u64(conditional_prefix_fields),
            fields,
        })
    }

    /// Converts this into a `TLDataDiscriminant`,
    /// allowing one to query which discriminant this is.
    pub const fn as_discriminant(&self) -> TLDataDiscriminant {
        match self {
            MonoTLData::Primitive { .. } => TLDataDiscriminant::Primitive,
            MonoTLData::Opaque { .. } => TLDataDiscriminant::Opaque,
            MonoTLData::Struct { .. } => TLDataDiscriminant::Struct,
            MonoTLData::Union { .. } => TLDataDiscriminant::Union,
            MonoTLData::Enum { .. } => TLDataDiscriminant::Enum,
            MonoTLData::PrefixType { .. } => TLDataDiscriminant::PrefixType,
        }
    }

    pub(super) const fn to_primitive(self) -> Option<TLPrimitive> {
        match self {
            MonoTLData::Primitive(x) => Some(x),
            _ => None,
        }
    }

    /// Expands this `MonoTLData`.
    ///
    /// # Errors
    ///
    /// This returns a `MismatchedTLDataVariant` if `self` and `generic`
    /// are variant of different names.
    pub fn expand(
        self,
        generic: GenericTLData,
        shared_vars: &'static SharedVars,
    ) -> Result<TLData, MismatchedTLDataVariant> {
        Ok(match (self, generic) {
            (MonoTLData::Primitive(prim), GenericTLData::Primitive) => TLData::Primitive(prim),
            (MonoTLData::Opaque, GenericTLData::Opaque) => TLData::Opaque,
            (MonoTLData::Struct { fields }, GenericTLData::Struct) => TLData::Struct {
                fields: fields.expand(shared_vars),
            },
            (MonoTLData::Union { fields }, GenericTLData::Union) => TLData::Union {
                fields: fields.expand(shared_vars),
            },
            (MonoTLData::Enum(nongeneric), GenericTLData::Enum(generic)) => {
                TLData::Enum(nongeneric.expand(generic, shared_vars))
            }
            (MonoTLData::PrefixType(nongeneric), GenericTLData::PrefixType(generic)) => {
                TLData::PrefixType(nongeneric.expand(generic, shared_vars))
            }
            _ => {
                return Err(MismatchedTLDataVariant {
                    nongeneric: self.as_discriminant(),
                    generic: generic.as_discriminant(),
                })
            }
        })
    }
}

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

/// An error returned by `MonoTLData::expand` because
/// the `GenericTLData` it tried to combine itself with was a different variant.
#[derive(Debug, Clone)]
pub struct MismatchedTLDataVariant {
    nongeneric: TLDataDiscriminant,
    generic: TLDataDiscriminant,
}

impl Display for MismatchedTLDataVariant {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(
            f,
            "Error combining TLData::{:?} and GenericTLData::{:?}",
            self.nongeneric, self.generic,
        )
    }
}

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

/// A discriminant-only version of TLData.
#[repr(u8)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, StableAbi)]
#[sabi(unsafe_sabi_opaque_fields)]
pub enum TLDataDiscriminant {
    ///
    Primitive,
    /// A type that's only compared for size and alignment.
    Opaque,
    ///
    Struct,
    ///
    Union,
    ///
    Enum,
    ///
    PrefixType,
}

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

/// The part of TLData that can change based on generic parameters.
#[repr(C)]
#[derive(Copy, Clone, StableAbi)]
#[sabi(unsafe_sabi_opaque_fields)]
pub enum GenericTLData {
    ///
    Primitive,
    /// A type that's only compared for size and alignment.
    Opaque,
    ///
    Struct,
    ///
    Union,
    ///
    Enum(GenericTLEnum),
    ///
    PrefixType(GenericTLPrefixType),
}

impl GenericTLData {
    /// Converts this into a `TLDataDiscriminant`,
    /// allowing one to query which discriminant this is.
    pub const fn as_discriminant(&self) -> TLDataDiscriminant {
        match self {
            GenericTLData::Primitive { .. } => TLDataDiscriminant::Primitive,
            GenericTLData::Opaque { .. } => TLDataDiscriminant::Opaque,
            GenericTLData::Struct { .. } => TLDataDiscriminant::Struct,
            GenericTLData::Union { .. } => TLDataDiscriminant::Union,
            GenericTLData::Enum { .. } => TLDataDiscriminant::Enum,
            GenericTLData::PrefixType { .. } => TLDataDiscriminant::PrefixType,
        }
    }

    #[doc(hidden)]
    pub const fn prefix_type_derive(accessible_fields: FieldAccessibility) -> Self {
        GenericTLData::PrefixType(GenericTLPrefixType { accessible_fields })
    }
}

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

/// The interior of the type definition,
/// describing whether the type is a primitive/enum/struct/union and its contents.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum TLData {
    /// Types defined in the compiler.
    Primitive(TLPrimitive),
    /// The type can't be inspected,and has no properties other than size/alignment.
    ///
    /// When translated to C,this would be a struct with a single array field
    /// whose element type is the alignment in this layout,
    /// with the same byte length as this layout .
    Opaque,
    /// For structs.
    Struct {
        ///
        fields: TLFields,
    },
    /// For unions.
    Union {
        ///
        fields: TLFields,
    },
    /// For enums.
    Enum(TLEnum),
    /// vtables and modules that can be extended in minor versions.
    PrefixType(TLPrefixType),
}

impl Display for TLData {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TLData::Primitive(prim) => {
                writeln!(f, "Primitive:{:?}", prim)?;
            }
            TLData::Opaque => {
                writeln!(f, "Opaque data")?;
            }
            TLData::Struct { fields } => {
                writeln!(
                    f,
                    "Struct with Fields:\n{}",
                    fields.to_string().left_padder(4)
                )?;
            }
            TLData::Union { fields } => {
                writeln!(
                    f,
                    "Union with Fields:\n{}",
                    fields.to_string().left_padder(4)
                )?;
            }
            TLData::Enum(enum_) => {
                writeln!(f, "Enum:")?;
                Display::fmt(enum_, f)?;
            }
            TLData::PrefixType(prefix) => {
                writeln!(f, "Prefix type:")?;
                Display::fmt(prefix, f)?;
            }
        }
        Ok(())
    }
}