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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
/*!
Types for modeling the layout of a datatype
*/

use std::{
    cell::RefCell,
    collections::HashSet,
    fmt::{self, Debug, Display, Formatter},
    mem,
};


use crate::{
    const_utils::empty_slice, version::VersionStrings, 
    std_types::{RNone, ROption, RSome, RStr, StaticSlice,StaticStr},
    ignored_wrapper::CmpIgnored,
    prefix_type::{FieldAccessibility,IsConditional},
};

use super::{
    AbiInfo, 
    GetAbiInfo,
    tagging::Tag,
};

/// The parameters for `TypeLayout::from_params`.
#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct TypeLayoutParams {
    pub name: &'static str,
    pub package: &'static str,
    pub package_version: VersionStrings,
    pub file:&'static str,
    pub line:u32,
    pub data: TLData,
    pub generics: GenericParams,
    pub phantom_fields: &'static [TLField],
    pub tag:Tag,
}


/// The layout of a type,
/// also includes metadata about where the type was defined.
#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq, StableAbi)]
// #[sabi(debug_print)]
#[sabi(inside_abi_stable_crate)]
pub struct TypeLayout {
    pub name: StaticStr,
    pub package: StaticStr,
    pub package_version: VersionStrings,
    pub file:CmpIgnored<StaticStr>, // This is for the Debug string
    pub line:CmpIgnored<u32>, // This is for the Debug string
    pub size: usize,
    pub alignment: usize,
    pub data: TLData,
    pub full_type: FullType,
    pub phantom_fields: StaticSlice<TLField>,
    pub tag:Tag,
}


/// Which lifetime is being referenced by a field.
/// Allows lifetimes to be renamed,so long as the "same" lifetime is being referenced.
#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, StableAbi)]
#[sabi(inside_abi_stable_crate)]
pub enum LifetimeIndex {
    Static,
    Param(usize),
}

/// Represents all the generic parameters of a type.
/// 
/// This is different for every different generic parameter,
/// if any one of them changes it won't compare equal,
/// `<Vec<u32>>::ABI_INFO.get().layout.full_type.generics`
/// ẁon't compare equal to
/// `<Vec<()>>::ABI_INFO.get().layout.full_type.generics`
/// 
///
#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq, StableAbi)]
#[sabi(inside_abi_stable_crate)]
pub struct GenericParams {
    pub lifetime: StaticSlice<StaticStr>,
    pub type_: StaticSlice<&'static TypeLayout>,
    pub const_: StaticSlice<StaticStr>,
}

/// The typename and generics of the type this layout is associated to,
/// used for printing types.
#[repr(C)]
#[derive(Copy, Clone, PartialEq, StableAbi)]
#[sabi(inside_abi_stable_crate)]
pub struct FullType {
    pub name: StaticStr,
    pub primitive: ROption<RustPrimitive>,
    pub generics: GenericParams,
}

/// What kind of type this is.struct/enum/etc.
///
/// Unions are currently treated as structs.
#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq, StableAbi)]
#[sabi(inside_abi_stable_crate)]
pub enum TLData {
    /// All the bytes for the type are valid (not necessarily all bit patterns).
    ///
    /// If you use this variant,
    /// you must ensure the continuing validity of the same bit-patterns.
    Primitive,
    /// For structs and unions.
    Struct { fields: StaticSlice<TLField> },
    /// For enums.
    Enum {
        variants: StaticSlice<TLEnumVariant>,
    },
    /// vtables and modules that can be extended in minor versions.
    PrefixType(TLPrefixType),
}


/// vtables and modules that can be extended in minor versions.
#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq, StableAbi)]
#[sabi(inside_abi_stable_crate)]
pub struct TLPrefixType {
    /// The first field in the suffix
    pub first_suffix_field:usize,
    pub accessible_fields:FieldAccessibility,
    pub conditional_prefix_fields:StaticSlice<IsConditional>,
    pub fields: StaticSlice<TLField>,
}



/// A discriminant-only version of TLData.
#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, StableAbi)]
#[sabi(inside_abi_stable_crate)]
pub enum TLDataDiscriminant {
    Primitive,
    Struct,
    Enum,
    PrefixType,
}

/// The layout of an enum variant.
#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq, StableAbi)]
#[sabi(inside_abi_stable_crate)]
pub struct TLEnumVariant {
    pub name: StaticStr,
    pub fields: StaticSlice<TLField>,
}

/// The layout of a field.
#[repr(C)]
#[derive(Copy, Clone, StableAbi)]
#[sabi(inside_abi_stable_crate)]
pub struct TLField {
    /// The field's name.
    pub name: StaticStr,
    /// Which lifetimes in the struct are referenced in the field type.
    pub lifetime_indices: StaticSlice<LifetimeIndex>,
    /// The layout of the field's type.
    ///
    /// This is a function pointer to avoid infinite recursion,
    /// if you have a `&'static AbiInfo`s with the same address as one of its parent type,
    /// you've encountered a cycle.
    pub abi_info: GetAbiInfo,
    /// Stores all extracted type parameters and return types of embedded function pointer types.
    pub subfields:StaticSlice<TLField>,
}

/// Used to print a field as its field and its type.
#[repr(transparent)]
#[derive(Copy, Clone, PartialEq, StableAbi)]
#[sabi(inside_abi_stable_crate)]
pub struct TLFieldAndType {
    inner: TLField,
}

/// What primitive type this is.Used mostly for printing the type.
#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, StableAbi)]
#[sabi(inside_abi_stable_crate)]
pub enum RustPrimitive {
    Reference,
    MutReference,
    ConstPtr,
    MutPtr,
    Array,
}

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

impl TLField {
    pub const fn new(
        name: &'static str,
        lifetime_indices: &'static [LifetimeIndex],
        abi_info: GetAbiInfo,
    ) -> Self {
        Self {
            name: StaticStr::new(name),
            lifetime_indices: StaticSlice::new(lifetime_indices),
            abi_info,
            subfields:StaticSlice::new(empty_slice()),
        }
    }

    pub const fn with_subfields(
        name: &'static str,
        lifetime_indices: &'static [LifetimeIndex],
        abi_info: GetAbiInfo,
        subfields:&'static [TLField],
    ) -> Self {
        Self {
            name: StaticStr::new(name),
            lifetime_indices: StaticSlice::new(lifetime_indices),
            abi_info,
            subfields: StaticSlice::new(subfields),
        }
    }

    /// Used for calling recursive methods,
    /// so as to avoid infinite recursion in types that reference themselves(even indirectly).
    fn recursive<F, U>(self, f: F) -> U
    where
        F: FnOnce(usize,TLFieldShallow) -> U,
    {
        let mut already_recursed = false;
        let mut recursion_depth=!0;
        let mut visited_nodes=!0;

        ALREADY_RECURSED.with(|state| {
            let mut state = state.borrow_mut();
            recursion_depth=state.recursion_depth;
            visited_nodes=state.visited_nodes;
            state.recursion_depth+=1;
            state.visited_nodes+=1;
            already_recursed = state.visited.replace(self.abi_info.get()).is_some();
        });

        let _guard=if visited_nodes==0 { Some(ResetRecursion) }else{ None };

        let field=TLFieldShallow::new(self, !already_recursed );
        let res = f( recursion_depth, field);

        ALREADY_RECURSED.with(|state| {
            let mut state = state.borrow_mut();
            state.recursion_depth-=1;
        });

        res
    }
}

impl PartialEq for TLField {
    fn eq(&self, other: &Self) -> bool {
        self.recursive(|_,this| {
            let r = TLFieldShallow::new(*other, this.abi_info.is_some());
            this == r
        })
    }
}

/// Need to avoid recursion somewhere,so I decided to stop at the field level.
impl Debug for TLField {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.recursive(|recursion_depth,x|{
            if recursion_depth>=2 {
                writeln!(f,"<printing recursion limit>")
            }else{
                fmt::Debug::fmt(&x, f)
            }
        })
    }
}

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


struct ResetRecursion;

impl Drop for ResetRecursion{
    fn drop(&mut self){
        ALREADY_RECURSED.with(|state|{
            let mut state = state.borrow_mut();
            state.recursion_depth=0;
            state.visited_nodes=0;
            state.visited.clear();
        });
    }
}


struct RecursionState{
    recursion_depth:usize,
    visited_nodes:u64,
    visited:HashSet<*const AbiInfo>,
}


thread_local! {
    static ALREADY_RECURSED: RefCell<RecursionState> = RefCell::new(RecursionState{
        recursion_depth:0,
        visited_nodes:0,
        visited: HashSet::default(),
    });
}

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

impl TLFieldAndType {
    pub fn new(inner: TLField) -> Self {
        Self { inner }
    }

    pub fn name(&self) -> RStr<'static> {
        self.inner.name.as_rstr()
    }

    pub fn full_type(&self) -> FullType {
        self.inner.abi_info.get().layout.full_type
    }
}

impl Debug for TLFieldAndType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TLFieldAndType")
            .field("field_name:", &self.inner.name)
            .field("type:", &self.inner.abi_info.get().layout.full_type())
            .finish()
    }
}

impl Display for TLFieldAndType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}:{}",
            self.inner.name,
            self.inner.abi_info.get().layout.full_type()
        )
    }
}

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

impl TypeLayout {
    








    pub(crate) const fn from_std_lib<T>(
        type_name: &'static str,
        data: TLData,
        generics: GenericParams,
    ) -> Self {
        Self::from_std_lib_phantom::<T>(type_name, RNone, data, generics, empty_slice())
    }

    pub(crate) const fn from_std_lib_phantom<T>(
        type_name: &'static str,
        prim: ROption<RustPrimitive>,
        data: TLData,
        genparams: GenericParams,
        phantom: &'static [TLField],
    ) -> Self {
        Self {
            name: StaticStr::new(type_name),
            package: StaticStr::new("std"),
            package_version: VersionStrings {
                major: StaticStr::new("1"),
                minor: StaticStr::new("0"),
                patch: StaticStr::new("0"),
            },
            file:CmpIgnored::new(StaticStr::new("<standard_library>")),
            line:CmpIgnored::new(0),
            size: mem::size_of::<T>(),
            alignment: mem::align_of::<T>(),
            data,
            full_type: FullType::new(type_name, prim, genparams),
            phantom_fields: StaticSlice::new(phantom),
            tag:Tag::null(),
        }
    }

    pub(crate) const fn full_type(&self) -> FullType {
        self.full_type
    }

    pub const fn from_params<T>(p: TypeLayoutParams) -> Self {
        let name = StaticStr::new(p.name);
        Self {
            name,
            package: StaticStr::new(p.package),
            package_version: p.package_version,
            file:CmpIgnored::new(StaticStr::new(p.file)),
            line:CmpIgnored::new(p.line),
            size: mem::size_of::<T>(),
            alignment: mem::align_of::<T>(),
            data: p.data,
            full_type: FullType {
                name,
                primitive: RNone,
                generics: p.generics,
            },
            phantom_fields: StaticSlice::new(p.phantom_fields),
            tag:p.tag,
        }
    }
}

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

impl GenericParams {
    pub const fn new(
        lifetime: &'static [StaticStr],
        type_: &'static [&'static TypeLayout],
        const_: &'static [StaticStr],
    ) -> Self {
        Self {
            lifetime: StaticSlice::new(lifetime),
            type_: StaticSlice::new(type_),
            const_: StaticSlice::new(const_),
        }
    }

    pub fn is_empty(&self) -> bool {
        self.lifetime.is_empty() && self.type_.is_empty() && self.const_.is_empty()
    }
}

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.lifetime.iter().cloned().enumerate() {
            fmt::Display::fmt(param.as_str(), &mut *f)?;
            post_iter(i, self.lifetime.len(), &mut *f)?;
        }
        for (i, param) in self.type_.iter().cloned().enumerate() {
            fmt::Debug::fmt(&param.full_type(), &mut *f)?;
            post_iter(i, self.type_.len(), &mut *f)?;
        }
        for (i, param) in self.const_.iter().cloned().enumerate() {
            fmt::Display::fmt(param.as_str(), &mut *f)?;
            post_iter(i, self.const_.len(), &mut *f)?;
        }
        fmt::Display::fmt(">", f)?;
        Ok(())
    }
}

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

impl TLData {
    pub const fn struct_(fields: &'static [TLField]) -> Self {
        TLData::Struct {
            fields: StaticSlice::new(fields),
        }
    }
    pub const fn enum_(variants: &'static [TLEnumVariant]) -> Self {
        TLData::Enum {
            variants: StaticSlice::new(variants),
        }
    }

    pub const fn prefix_type(
        first_suffix_field:usize,
        accessible_fields:FieldAccessibility,
        conditional_prefix_fields:&'static [IsConditional],
        fields: &'static [TLField],
    )->Self{
        TLData::PrefixType(TLPrefixType{
            first_suffix_field,
            accessible_fields,
            conditional_prefix_fields:StaticSlice::new(conditional_prefix_fields),
            fields:StaticSlice::new(fields),
        })
    }

    pub fn discriminant(&self) -> TLDataDiscriminant {
        match self {
            TLData::Primitive { .. } => TLDataDiscriminant::Primitive,
            TLData::Struct { .. } => TLDataDiscriminant::Struct,
            TLData::Enum { .. } => TLDataDiscriminant::Enum,
            TLData::PrefixType { .. } => TLDataDiscriminant::PrefixType,
        }
    }
}

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

impl TLEnumVariant {
    pub const fn new(name: &'static str, fields: &'static [TLField]) -> Self {
        Self {
            name: StaticStr::new(name),
            fields: StaticSlice::new(fields),
        }
    }
}

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

impl FullType {
    pub const fn new(
        name: &'static str,
        primitive: ROption<RustPrimitive>,
        generics: GenericParams,
    ) -> Self {
        Self {
            name: StaticStr::new(name),
            primitive,
            generics,
        }
    }
}

impl Display for FullType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Debug::fmt(self, f)
    }
}
impl Debug for FullType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let (typename, start_gen, before_ty, ty_sep, end_gen) = match self.primitive {
            RSome(RustPrimitive::Reference) => ("&", "", " ", " ", " "),
            RSome(RustPrimitive::MutReference) => ("&", "", " mut ", " ", " "),
            RSome(RustPrimitive::ConstPtr) => ("*const", " ", "", " ", " "),
            RSome(RustPrimitive::MutPtr) => ("*mut", " ", "", " ", " "),
            RSome(RustPrimitive::Array) => ("", "[", "", ";", "]"),
            RNone => (self.name.as_str(), "<", "", ", ", ">"),
        };

        fmt::Display::fmt(typename, f)?;
        let mut is_before_ty = true;
        let generics = self.generics;
        if !generics.is_empty() {
            fmt::Display::fmt(start_gen, f)?;

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

            let mut i=0;

            let total_generics_len=
                generics.lifetime.len()+generics.type_.len()+generics.const_.len();

            for param in generics.lifetime.iter().cloned() {
                fmt::Display::fmt(param.as_str(), &mut *f)?;
                post_iter(i,total_generics_len, &mut *f)?;
                i+=1;
            }
            for param in generics.type_.iter().cloned() {
                if is_before_ty {
                    fmt::Display::fmt(before_ty, &mut *f)?;
                    is_before_ty = false;
                }
                fmt::Debug::fmt(&param.full_type(), &mut *f)?;
                post_iter(i,total_generics_len, &mut *f)?;
                i+=1;
            }
            for param in generics.const_.iter().cloned() {
                fmt::Display::fmt(param.as_str(), &mut *f)?;
                post_iter(i,total_generics_len, &mut *f)?;
                i+=1;
            }
            fmt::Display::fmt(end_gen, f)?;
        }
        Ok(())
    }
}

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

#[derive(Debug, Copy, Clone, PartialEq)]
struct TLFieldShallow {
    pub(crate) name: StaticStr,
    pub(crate) full_type: FullType,
    pub(crate) lifetime_indices: StaticSlice<LifetimeIndex>,
    /// This is None if it already printed that AbiInfo
    pub(crate) abi_info: Option<&'static AbiInfo>,
}

impl TLFieldShallow {
    fn new(field: TLField, include_abi_info: bool) -> Self {
        let abi_info = field.abi_info.get();
        TLFieldShallow {
            name: field.name,
            lifetime_indices: field.lifetime_indices,
            abi_info: if include_abi_info {
                Some(abi_info)
            } else {
                None
            },
            full_type: abi_info.layout.full_type,
        }
    }
}