rudy-types 0.4.3

Type layouts of common Rust types for Rudy
Documentation
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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
//! Definition of types in the Rust language.

use std::{mem::size_of, sync::Arc};

use itertools::Itertools;
use salsa::Update;

impl Location for () {}

impl<L: Location> Layout<L> {
    pub fn display_name(&self) -> String {
        match &self {
            Layout::Primitive(primitive_def) => match primitive_def {
                PrimitiveLayout::Array(array_def) => format!(
                    "[{}; {}]",
                    array_def.element_type.display_name(),
                    array_def.length
                ),
                PrimitiveLayout::Bool(_) => "bool".to_string(),
                PrimitiveLayout::Char(_) => "char".to_string(),
                PrimitiveLayout::Float(float_def) => {
                    format!("f{}", float_def.size * 8)
                }
                PrimitiveLayout::Function(function_def) => function_def.display_name(),
                PrimitiveLayout::Int(int_def) => int_def.display_name(),
                PrimitiveLayout::Never(_) => "!".to_string(),
                PrimitiveLayout::Pointer(pointer_def) => {
                    format!("*{}", pointer_def.pointed_type.display_name())
                }
                PrimitiveLayout::Reference(reference_def) => {
                    let mut_ref = if reference_def.mutable { "mut " } else { "" };
                    format!("&{}{}", mut_ref, reference_def.pointed_type.display_name())
                }
                PrimitiveLayout::Slice(slice_def) => {
                    format!("&[{}]", slice_def.element_type.display_name())
                }
                PrimitiveLayout::Str(_) => "str".to_string(),
                PrimitiveLayout::StrSlice(_) => "&str".to_string(),
                PrimitiveLayout::Tuple(tuple_def) => {
                    let elements = tuple_def
                        .elements
                        .iter()
                        .map(|(_, element)| element.display_name())
                        .join(", ");
                    format!("({elements})")
                }
                PrimitiveLayout::Unit(_) => "()".to_string(),
                PrimitiveLayout::UnsignedInt(unsigned_int_def) => unsigned_int_def.display_name(),
            },
            Layout::Std(std_def) => match std_def {
                StdLayout::SmartPtr(smart_ptr_def) => {
                    let inner = smart_ptr_def.inner_type.display_name();
                    match smart_ptr_def.variant {
                        SmartPtrVariant::Box => format!("Box<{inner}>"),
                        _ => format!("{:?}<{}>", smart_ptr_def.variant, inner),
                    }
                }
                StdLayout::Map(map_def) => map_def.display_name(),
                StdLayout::Option(option_def) => {
                    let inner_type = option_def.some_type.display_name();
                    format!("Option<{inner_type}>")
                }
                StdLayout::Result(result_def) => {
                    let ok_type = result_def.ok_type.display_name();
                    let err_type = result_def.err_type.display_name();
                    format!("Result<{ok_type}, {err_type}>")
                }
                StdLayout::String(_) => "String".to_string(),
                StdLayout::Vec(vec_def) => {
                    let inner_type = vec_def.inner_type.display_name();
                    format!("Vec<{inner_type}>")
                }
            },
            Layout::Struct(struct_def) => struct_def.name.clone(),
            Layout::Enum(enum_def) => enum_def.name.clone(),
            Layout::CEnum(c_enum_def) => c_enum_def.name.clone(),
            Layout::Alias { name } => name.to_string(),
        }
    }

    pub fn size(&self) -> Option<usize> {
        match &self {
            Layout::Primitive(primitive_def) => primitive_def.size(),
            Layout::Std(std_def) => std_def.size(),
            Layout::Struct(struct_def) => Some(struct_def.size),
            Layout::Enum(enum_def) => Some(enum_def.size),
            Layout::CEnum(c_enum_def) => Some(c_enum_def.size),
            Layout::Alias { name: _ } => None,
        }
    }

    pub fn matching_type(&self, other: &Layout<L>) -> bool {
        match (self, other) {
            (Layout::Primitive(p1), Layout::Primitive(p2)) => p1.matching_type(p2),
            (Layout::Std(s1), Layout::Std(s2)) => s1.matching_type(s2),
            (Layout::Struct(s1), Layout::Struct(s2)) => s1.name == s2.name,
            (Layout::Struct(s1), Layout::Alias { name }) => &s1.name == name,
            (Layout::Alias { name: left }, Layout::Alias { name: right }) => left == right,
            (Layout::Alias { name }, x) | (x, Layout::Alias { name }) => name == &x.display_name(),
            (Layout::Enum(e1), Layout::Enum(e2)) => e1.name == e2.name,
            (Layout::CEnum(e1), Layout::CEnum(e2)) => e1.name == e2.name,
            _ => false,
        }
    }

    pub fn as_reference(&self, location: L) -> Layout<L>
    where
        Self: Clone,
    {
        Layout::Primitive(PrimitiveLayout::Reference(ReferenceLayout {
            mutable: false,
            pointed_type: TypeDefinition::new(location, self.clone()),
        }))
    }

    pub fn dereferenced(&self) -> &Layout<L> {
        match self {
            Layout::Primitive(PrimitiveLayout::Pointer(pointer_def)) => {
                pointer_def.pointed_type.layout.dereferenced()
            }
            Layout::Primitive(PrimitiveLayout::Reference(reference_def)) => {
                reference_def.pointed_type.layout.dereferenced()
            }
            _ => {
                // If it's not a pointer or reference, return self
                self
            }
        }
    }
}

// Conversion helpers for cleaner test code
impl<L: Location> From<PrimitiveLayout<L>> for Layout<L> {
    fn from(primitive: PrimitiveLayout<L>) -> Self {
        Layout::Primitive(primitive)
    }
}

impl<L: Location> From<StdLayout<L>> for Layout<L> {
    fn from(std_def: StdLayout<L>) -> Self {
        Layout::Std(std_def)
    }
}

impl<L: Location> From<StructLayout<L>> for Layout<L> {
    fn from(struct_def: StructLayout<L>) -> Self {
        Layout::Struct(struct_def)
    }
}

impl<L: Location> From<EnumLayout<L>> for Layout<L> {
    fn from(enum_def: EnumLayout<L>) -> Self {
        Layout::Enum(enum_def)
    }
}

// PrimitiveDef conversions
impl<L: Location> From<ArrayLayout<L>> for PrimitiveLayout<L> {
    fn from(array: ArrayLayout<L>) -> Self {
        PrimitiveLayout::Array(array)
    }
}

impl<L: Location> From<FloatLayout> for PrimitiveLayout<L> {
    fn from(float: FloatLayout) -> Self {
        PrimitiveLayout::Float(float)
    }
}

impl<L: Location> From<FunctionLayout<L>> for PrimitiveLayout<L> {
    fn from(function: FunctionLayout<L>) -> Self {
        PrimitiveLayout::Function(function)
    }
}

impl<L: Location> From<IntLayout> for PrimitiveLayout<L> {
    fn from(int: IntLayout) -> Self {
        PrimitiveLayout::Int(int)
    }
}

impl<L: Location> From<PointerLayout<L>> for PrimitiveLayout<L> {
    fn from(pointer: PointerLayout<L>) -> Self {
        PrimitiveLayout::Pointer(pointer)
    }
}

impl<L: Location> From<ReferenceLayout<L>> for PrimitiveLayout<L> {
    fn from(reference: ReferenceLayout<L>) -> Self {
        PrimitiveLayout::Reference(reference)
    }
}

impl<L: Location> From<SliceLayout<L>> for PrimitiveLayout<L> {
    fn from(slice: SliceLayout<L>) -> Self {
        PrimitiveLayout::Slice(slice)
    }
}

impl<L: Location> From<StrSliceLayout> for PrimitiveLayout<L> {
    fn from(str_slice: StrSliceLayout) -> Self {
        PrimitiveLayout::StrSlice(str_slice)
    }
}

impl<L: Location> From<TupleLayout<L>> for PrimitiveLayout<L> {
    fn from(tuple: TupleLayout<L>) -> Self {
        PrimitiveLayout::Tuple(tuple)
    }
}

impl<L: Location> From<UnitLayout> for PrimitiveLayout<L> {
    fn from(unit: UnitLayout) -> Self {
        PrimitiveLayout::Unit(unit)
    }
}

impl<L: Location> From<UnsignedIntLayout> for PrimitiveLayout<L> {
    fn from(uint: UnsignedIntLayout) -> Self {
        PrimitiveLayout::UnsignedInt(uint)
    }
}

// StdDef conversions
impl<L: Location> From<SmartPtrLayout<L>> for StdLayout<L> {
    fn from(smart_ptr: SmartPtrLayout<L>) -> Self {
        StdLayout::SmartPtr(smart_ptr)
    }
}

impl<L: Location> From<MapLayout<L>> for StdLayout<L> {
    fn from(map: MapLayout<L>) -> Self {
        StdLayout::Map(map)
    }
}

impl<L: Location> From<StringLayout<L>> for StdLayout<L> {
    fn from(string: StringLayout<L>) -> Self {
        StdLayout::String(string)
    }
}

impl<L: Location> From<VecLayout<L>> for StdLayout<L> {
    fn from(vec: VecLayout<L>) -> Self {
        StdLayout::Vec(vec)
    }
}

// Convenience constructors for primitives with unit values
impl<L: Location> From<()> for PrimitiveLayout<L> {
    fn from(_: ()) -> Self {
        PrimitiveLayout::Bool(())
    }
}

// Chain conversions for common patterns
impl<L: Location> From<UnsignedIntLayout> for Layout<L> {
    fn from(uint: UnsignedIntLayout) -> Self {
        Layout::Primitive(PrimitiveLayout::UnsignedInt(uint))
    }
}

impl<L: Location> From<IntLayout> for Layout<L> {
    fn from(int: IntLayout) -> Self {
        Layout::Primitive(PrimitiveLayout::Int(int))
    }
}

impl<L: Location> From<FloatLayout> for Layout<L> {
    fn from(float: FloatLayout) -> Self {
        Layout::Primitive(PrimitiveLayout::Float(float))
    }
}

impl<L: Location> From<ReferenceLayout<L>> for Layout<L> {
    fn from(reference: ReferenceLayout<L>) -> Self {
        Layout::Primitive(PrimitiveLayout::Reference(reference))
    }
}

impl<L: Location> From<StringLayout<L>> for Layout<L> {
    fn from(string: StringLayout<L>) -> Self {
        Layout::Std(StdLayout::String(string))
    }
}

impl<L: Location> From<VecLayout<L>> for Layout<L> {
    fn from(vec: VecLayout<L>) -> Self {
        Layout::Std(StdLayout::Vec(vec))
    }
}

impl<L: Location> From<MapLayout<L>> for Layout<L> {
    fn from(map: MapLayout<L>) -> Self {
        Layout::Std(StdLayout::Map(map))
    }
}

impl<L: Location> From<SmartPtrLayout<L>> for Layout<L> {
    fn from(smart_ptr: SmartPtrLayout<L>) -> Self {
        Layout::Std(StdLayout::SmartPtr(smart_ptr))
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Hash, Update)]
pub struct TypeDefinition<L = ()>
where
    L: Location,
{
    /// The layout of the type definition
    ///
    /// This is an owned reference to the layout,
    /// so it can be shared across multiple definitions
    pub layout: Arc<Layout<L>>,

    /// The location of the type definition in the DWARF
    /// information. This is used to resolve
    /// the type definition in the debug information.
    pub location: L,
}

impl<L> TypeDefinition<L>
where
    L: Location,
{
    pub fn new(location: L, layout: Layout<L>) -> Self {
        Self {
            layout: Arc::new(layout),
            location,
        }
    }

    pub fn display_name(&self) -> String {
        self.layout.display_name()
    }

    pub fn size(&self) -> Option<usize> {
        self.layout.size()
    }

    pub fn matching_type(&self, other: &Self) -> bool {
        self.location.matches(&other.location) || self.layout.matching_type(&other.layout)
    }
}

pub trait Location: Update {
    fn matches(&self, _other: &Self) -> bool {
        // Default implementation for `()` (no location)
        // This can be overridden by specific location types
        false
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Hash, Update)]
pub enum Layout<L = ()>
where
    L: Location,
{
    /// Language-specific primitive types from `core::primitive`
    /// (e.g. `i32`, `f64`, etc.)
    ///
    /// There are all simple types that can
    /// be backed by a single slice of memory
    /// and easily transumted to a Rust type
    Primitive(PrimitiveLayout<L>),

    /// Common definitions from the Rust standard library
    Std(StdLayout<L>),

    // Custom type definitions
    /// Structs and tuples
    Struct(StructLayout<L>),

    /// Enums
    Enum(EnumLayout<L>),

    /// C-style enumerations (simple named integer constants)
    CEnum(CEnumLayout),

    /// Type currently known only by its name
    Alias { name: String },
}

/// From the Rust standard library:
#[derive(Debug, PartialEq, Eq, Clone, Hash, Update)]
pub enum PrimitiveLayout<L = ()>
where
    L: Location,
{
    Array(ArrayLayout<L>),
    Bool(()),
    Char(()),
    Float(FloatLayout),
    Function(FunctionLayout<L>),
    Int(IntLayout),
    Never(()),
    Pointer(PointerLayout<L>),
    Reference(ReferenceLayout<L>),
    Slice(SliceLayout<L>),
    /// Technically constructable, `str` is like `[u8; N]`
    /// but where the size is opaque (since utf8 is variable length)
    /// and so rarely seen in the wild. We could have something like `Box<str>`
    /// though.
    Str(()),
    /// A specialization of `Slice` where the referenced type is `str`
    /// Also helps us avoid using the `str` type.
    StrSlice(StrSliceLayout),
    Tuple(TupleLayout<L>),
    Unit(UnitLayout),
    UnsignedInt(UnsignedIntLayout),
    // neverExperimental,
}

impl<L: Location> PrimitiveLayout<L> {
    fn size(&self) -> Option<usize> {
        let size = match self {
            PrimitiveLayout::Array(array_def) => {
                let element_size = array_def.element_type.size()?;
                element_size * array_def.length
            }
            PrimitiveLayout::Bool(_) => {
                // bool is 1 byte
                1
            }
            PrimitiveLayout::Char(_) => {
                // char is 4 bytes
                4
            }
            PrimitiveLayout::Float(float_def) => float_def.size,
            PrimitiveLayout::Function(_)
            | PrimitiveLayout::Pointer(_)
            | PrimitiveLayout::Reference(_) => {
                // size of a pointer
                size_of::<usize>()
            }
            PrimitiveLayout::Int(int_def) => {
                // size of an int
                int_def.size
            }
            PrimitiveLayout::Never(_) => {
                // never type is 0 bytes
                0
            }
            PrimitiveLayout::Slice(_) => size_of::<&[u8]>(),
            PrimitiveLayout::Str(_) => unimplemented!(),
            PrimitiveLayout::StrSlice(_) => size_of::<&str>(),
            PrimitiveLayout::Tuple(tuple_def) => tuple_def.size,
            PrimitiveLayout::Unit(_) => 0,
            PrimitiveLayout::UnsignedInt(unsigned_int_def) => {
                // size of an unsigned int
                unsigned_int_def.size
            }
        };

        Some(size)
    }

    fn matching_type(&self, other: &Self) -> bool {
        use PrimitiveLayout::*;
        match (self, other) {
            (Pointer(l), Pointer(r)) => l.pointed_type.matching_type(&r.pointed_type),
            (Reference(l), Reference(r)) => l.pointed_type.matching_type(&r.pointed_type),
            (Slice(l), Slice(r)) => l.element_type.matching_type(&r.element_type),
            (Array(l), Array(r)) => l.element_type.matching_type(&r.element_type),
            (Tuple(l), Tuple(r)) => {
                if l.elements.len() != r.elements.len() {
                    return false;
                }
                l.elements
                    .iter()
                    .zip(r.elements.iter())
                    .all(|((_, l), (_, r))| l.matching_type(r))
            }

            (Function(l), Function(r)) => {
                l.arg_types.len() == r.arg_types.len()
                    && l.return_type.is_none() == r.return_type.is_none()
                    && l.return_type
                        .as_ref()
                        .zip(r.return_type.as_ref())
                        .is_none_or(|(l_ret, r_ret)| l_ret.matching_type(r_ret))
                    && l.arg_types
                        .iter()
                        .zip(r.arg_types.iter())
                        .all(|(l_arg, r_arg)| l_arg.matching_type(r_arg))
            }
            (Bool(_), Bool(_))
            | (Char(_), Char(_))
            | (Never(_), Never(_))
            | (Str(_), Str(_))
            | (Unit(_), Unit(_)) => true,
            (Float(l), Float(r)) => l == r,
            (Int(l), Int(r)) => l == r,
            (UnsignedInt(l), UnsignedInt(r)) => l == r,

            (StrSlice(l), StrSlice(r)) => l == r,
            _ => false,
        }
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Hash, Update)]
pub struct ArrayLayout<L = ()>
where
    L: Location,
{
    pub element_type: TypeDefinition<L>,
    pub length: usize,
}

#[derive(Debug, PartialEq, Eq, Clone, Hash, Update, Copy)]
pub struct FloatLayout {
    pub size: usize,
}
#[derive(Debug, PartialEq, Eq, Clone, Hash, Update)]
pub struct FunctionLayout<L = ()>
where
    L: Location,
{
    pub return_type: Option<TypeDefinition<L>>,
    pub arg_types: Vec<TypeDefinition<L>>,
}

impl<L: Location> FunctionLayout<L> {
    pub fn display_name(&self) -> String {
        let arg_types = self
            .arg_types
            .iter()
            .map(|arg| arg.display_name())
            .collect::<Vec<_>>()
            .join(", ");

        let mut signature = format!("fn({arg_types})");

        if let Some(l) = self.return_type.as_ref() {
            signature += &format!(" -> {}", l.display_name());
        }
        signature
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Hash, Update, Copy)]
pub struct IntLayout {
    pub size: usize,
}

impl IntLayout {
    pub fn display_name(&self) -> String {
        format!("i{}", self.size * 8)
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Hash, Update)]
pub struct PointerLayout<L = ()>
where
    L: Location,
{
    pub mutable: bool,
    pub pointed_type: TypeDefinition<L>,
}
#[derive(Debug, PartialEq, Eq, Clone, Hash, Update)]
pub struct ReferenceLayout<L = ()>
where
    L: Location,
{
    /// Is this a mutable reference?
    /// (i.e. `&mut T` vs `&T`)
    pub mutable: bool,

    pub pointed_type: TypeDefinition<L>,
}

#[derive(Debug, PartialEq, Eq, Clone, Hash, Update)]
pub struct SliceLayout<L = ()>
where
    L: Location,
{
    pub element_type: TypeDefinition<L>,
    pub data_ptr_offset: usize,
    pub length_offset: usize,
}

#[derive(Debug, PartialEq, Eq, Clone, Hash, Update)]
pub struct StrSliceLayout {
    pub data_ptr_offset: usize,
    pub length_offset: usize,
}

#[derive(Debug, PartialEq, Eq, Clone, Hash, Update)]
pub struct TupleLayout<L = ()>
where
    L: Location,
{
    /// List of elements + offsets to their data
    pub elements: Vec<(usize, TypeDefinition<L>)>,
    pub size: usize,
}
#[derive(Debug, PartialEq, Eq, Clone, Hash, Update)]
pub struct UnitLayout;

#[derive(Debug, PartialEq, Eq, Clone, Hash, Update, Copy)]
pub struct UnsignedIntLayout {
    /// Size in bytes
    /// (e.g. 1 for u8, 2 for u16, etc.)
    pub size: usize,
}

impl UnsignedIntLayout {
    pub fn display_name(&self) -> String {
        format!("u{}", self.size * 8)
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Hash, Update)]
pub enum StdLayout<L = ()>
where
    L: Location,
{
    SmartPtr(SmartPtrLayout<L>),
    Map(MapLayout<L>),
    Option(OptionLayout<L>),
    Result(ResultLayout<L>),
    String(StringLayout<L>),
    Vec(VecLayout<L>),
}

impl<L: Location> StdLayout<L> {
    fn size(&self) -> Option<usize> {
        let size = match self {
            StdLayout::SmartPtr(smart_ptr_def) => match smart_ptr_def.variant {
                SmartPtrVariant::Box => size_of::<Box<()>>(),
                SmartPtrVariant::Rc => size_of::<std::rc::Rc<()>>(),
                SmartPtrVariant::Arc => size_of::<std::sync::Arc<()>>(),
                SmartPtrVariant::RefCell => size_of::<std::cell::RefCell<()>>(),
                SmartPtrVariant::Mutex => size_of::<std::sync::Mutex<()>>(),
                SmartPtrVariant::RwLock => size_of::<std::sync::RwLock<()>>(),
                SmartPtrVariant::Cell => size_of::<std::cell::Cell<()>>(),
                SmartPtrVariant::UnsafeCell => size_of::<std::cell::UnsafeCell<()>>(),
            },
            StdLayout::Map(map_def) => match map_def.variant {
                MapVariant::HashMap { .. } => size_of::<std::collections::HashMap<(), ()>>(),
                MapVariant::BTreeMap { .. } => size_of::<std::collections::BTreeMap<(), ()>>(),
                MapVariant::IndexMap => unimplemented!(),
            },
            StdLayout::Option(def) => def.size,
            StdLayout::Result(def) => def.size,
            StdLayout::String(_) | StdLayout::Vec(_) => size_of::<Vec<()>>(),
        };

        Some(size)
    }

    fn matching_type(&self, other: &Self) -> bool {
        match (self, other) {
            (StdLayout::SmartPtr(l), StdLayout::SmartPtr(r)) => {
                l.variant == r.variant && l.inner_type.matching_type(&r.inner_type)
            }
            (StdLayout::Map(l), StdLayout::Map(r)) => {
                l.variant == r.variant
                    && l.key_type.matching_type(&r.key_type)
                    && l.value_type.matching_type(&r.value_type)
            }
            (StdLayout::Option(l), StdLayout::Option(r)) => l.some_type.matching_type(&r.some_type),
            (StdLayout::Result(l), StdLayout::Result(r)) => {
                l.ok_type.matching_type(&r.ok_type) && l.err_type.matching_type(&r.err_type)
            }
            (StdLayout::String(_), StdLayout::String(_)) => true,
            (StdLayout::Vec(l), StdLayout::Vec(r)) => l.inner_type.matching_type(&r.inner_type),
            _ => false,
        }
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Hash, Update)]
pub struct SmartPtrLayout<L = ()>
where
    L: Location,
{
    pub inner_type: TypeDefinition<L>,
    pub inner_ptr_offset: usize,
    pub data_ptr_offset: usize,
    pub variant: SmartPtrVariant,
}

#[derive(Debug, PartialEq, Eq, Clone, Hash, Update, Copy)]
pub enum SmartPtrVariant {
    Box,
    Rc,
    Arc,
    RefCell,
    Mutex,
    RwLock,
    Cell,
    UnsafeCell,
}

impl SmartPtrVariant {
    pub fn name(&self) -> &'static str {
        match self {
            SmartPtrVariant::Box => "Box",
            SmartPtrVariant::Rc => "Rc",
            SmartPtrVariant::Arc => "Arc",
            SmartPtrVariant::RefCell => "RefCell",
            SmartPtrVariant::Mutex => "Mutex",
            SmartPtrVariant::RwLock => "RwLock",
            SmartPtrVariant::Cell => "Cell",
            SmartPtrVariant::UnsafeCell => "UnsafeCell",
        }
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Hash, Update)]
pub struct MapLayout<L = ()>
where
    L: Location,
{
    pub key_type: TypeDefinition<L>,
    pub value_type: TypeDefinition<L>,
    pub variant: MapVariant,
}

impl<L: Location> MapLayout<L> {
    pub fn display_name(&self) -> String {
        format!(
            "{}<{}, {}>",
            self.variant.name(),
            self.key_type.display_name(),
            self.value_type.display_name()
        )
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Hash, Update)]
pub struct BTreeRootLayout {
    pub node_offset: usize,   // offset to node field within Root
    pub height_offset: usize, // offset to height field within Root
}

#[derive(Debug, PartialEq, Eq, Clone, Hash, Update)]
pub struct BTreeNodeLayout {
    pub keys_offset: usize,  // offset to keys array in LeafNode
    pub vals_offset: usize,  // offset to vals array in LeafNode
    pub len_offset: usize,   // offset to len field in LeafNode
    pub edges_offset: usize, // offset to edges array in InternalNode
}

#[derive(Debug, PartialEq, Eq, Clone, Hash, Update)]
pub enum MapVariant {
    HashMap {
        bucket_mask_offset: usize, // offset within RawTableInner
        ctrl_offset: usize,        // offset to ctrl pointer
        items_offset: usize,       // offset to items count
        pair_size: usize,          // size of a single key-value pair
        key_offset: usize,         // offset to key within a pair
        value_offset: usize,       // offset to value within a pair
    },
    BTreeMap {
        length_offset: usize,         // offset to length field in BTreeMap
        root_offset: usize,           // offset to root field in BTreeMap
        root_layout: BTreeRootLayout, // layout of the root structure
        node_layout: BTreeNodeLayout, // layout of the node structures
    },
    IndexMap,
}

impl MapVariant {
    pub fn name(&self) -> &'static str {
        match self {
            MapVariant::HashMap { .. } => "HashMap",
            MapVariant::BTreeMap { .. } => "BTreeMap",
            MapVariant::IndexMap => "IndexMap",
        }
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Hash, Update)]
pub struct StringLayout<L = ()>(pub VecLayout<L>)
where
    L: Location;

#[derive(Debug, PartialEq, Eq, Clone, Hash, Update)]
pub struct VecLayout<L = ()>
where
    L: Location,
{
    /// Offset to the length field (vec.len)
    pub length_offset: usize,
    /// Offset to the data pointer (vec.buf.inner.ptr.pointer)
    pub data_ptr_offset: usize,
    /// Offset to the capacity value (vec.buf.inner.cap.__0)
    pub capacity_offset: usize,
    /// The element type of the Vec
    pub inner_type: TypeDefinition<L>,
}

impl<L: Location + Default> VecLayout<L> {
    pub fn new<T: Into<Layout<L>>>(inner_type: T) -> Self {
        Self {
            length_offset: 0,
            data_ptr_offset: 0,
            capacity_offset: 0,
            inner_type: TypeDefinition::new(Default::default(), inner_type.into()),
        }
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Hash, Update)]
pub struct StructLayout<L = ()>
where
    L: Location,
{
    pub name: String,
    pub size: usize,
    pub alignment: usize,
    pub fields: Vec<StructField<L>>,
}
#[derive(Debug, PartialEq, Eq, Clone, Hash, Update)]
pub struct StructField<L = ()>
where
    L: Location,
{
    pub name: String,
    pub offset: usize,
    pub ty: TypeDefinition<L>,
}

#[derive(Debug, PartialEq, Eq, Clone, Hash, Update)]
pub struct Discriminant {
    pub ty: DiscriminantType,
    pub offset: usize,
}

impl Discriminant {
    pub fn size(&self) -> usize {
        match &self.ty {
            DiscriminantType::Int(int_def) => int_def.size,
            DiscriminantType::UnsignedInt(unsigned_int_def) => unsigned_int_def.size,
            DiscriminantType::Implicit => 4, // no idea?
        }
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Hash, Update)]
pub enum DiscriminantType {
    Int(IntLayout),
    UnsignedInt(UnsignedIntLayout),
    Implicit,
}

#[derive(Debug, PartialEq, Eq, Clone, Hash, Update)]
pub struct EnumLayout<L = ()>
where
    L: Location,
{
    pub name: String,
    pub discriminant: Discriminant,
    pub variants: Vec<EnumVariantLayout<L>>,
    pub size: usize,
}

#[derive(Debug, PartialEq, Eq, Clone, Hash, Update)]
pub struct EnumVariantLayout<L = ()>
where
    L: Location,
{
    pub name: String,
    /// The discriminant value for this variant, if known
    ///
    /// If `None`, we should use the index of the variant
    /// in the `variants` vector as the discriminant value.
    pub discriminant: Option<i128>,
    pub layout: TypeDefinition<L>,
}

#[derive(Debug, PartialEq, Eq, Clone, Hash, Update)]
pub struct OptionLayout<L = ()>
where
    L: Location,
{
    pub name: String,
    pub discriminant: Discriminant,
    pub some_offset: usize,
    pub some_type: TypeDefinition<L>,
    pub size: usize,
}

#[derive(Debug, PartialEq, Eq, Clone, Hash, Update)]
pub struct ResultLayout<L = ()>
where
    L: Location,
{
    pub name: String,
    pub discriminant: Discriminant,
    pub ok_type: TypeDefinition<L>,
    pub ok_offset: usize,
    pub err_type: TypeDefinition<L>,
    pub err_offset: usize,
    pub size: usize,
}

#[derive(Debug, PartialEq, Eq, Clone, Hash, Update)]
pub struct CEnumLayout {
    pub name: String,
    pub discriminant_type: DiscriminantType,
    pub variants: Vec<CEnumVariant>,
    pub size: usize,
}

#[derive(Debug, PartialEq, Eq, Clone, Hash, Update)]
pub struct CEnumVariant {
    pub name: String,
    pub value: i128,
}

// Helper functions for common patterns
impl UnsignedIntLayout {
    pub fn u8() -> Self {
        Self { size: 1 }
    }
    pub fn u32() -> Self {
        Self { size: 4 }
    }
    pub fn u64() -> Self {
        Self { size: 8 }
    }
}

impl IntLayout {
    pub fn i32() -> Self {
        Self { size: 4 }
    }
}

impl<L: Location + Default> ReferenceLayout<L> {
    pub fn new_mutable<T: Into<Layout<L>>>(pointed_type: T) -> Self {
        Self {
            mutable: true,
            pointed_type: TypeDefinition::new(Default::default(), pointed_type.into()),
        }
    }

    pub fn new_immutable<T: Into<Layout<L>>>(pointed_type: T) -> Self {
        Self {
            mutable: false,
            pointed_type: TypeDefinition::new(Default::default(), pointed_type.into()),
        }
    }
}