dotscope 0.6.0

A high-performance, cross-platform framework for analyzing and reverse engineering .NET PE executables
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
//! High-level class builder for creating complete .NET type definitions.
//!
//! This module provides [`ClassBuilder`] for creating complete class definitions
//! including fields, methods, properties, and other members. It orchestrates
//! the existing low-level builders to provide a fluent, high-level API.

use crate::{
    cilassembly::{ChangeRefRc, CilAssembly},
    metadata::{
        signatures::{encode_field_signature, SignatureField, TypeSignature},
        tables::{
            CodedIndex, CodedIndexType, FieldBuilder, InterfaceImplBuilder, TypeAttributes,
            TypeDefBuilder,
        },
        token::Token,
    },
    Error, Result,
};

// Use field attributes constants directly from the tables module

use super::method::MethodBuilder;

/// Field definition for the class builder.
struct FieldDefinition {
    name: String,
    field_type: TypeSignature,
    attributes: u32,
}

/// Property definition for the class builder.
struct PropertyDefinition {
    name: String,
    property_type: TypeSignature,
    has_getter: bool,
    has_setter: bool,
    backing_field_name: Option<String>,
}

/// High-level builder for creating complete class definitions.
///
/// `ClassBuilder` provides a fluent API for creating classes with fields,
/// methods, properties, and other members. It composes the existing
/// low-level builders to provide a convenient high-level interface.
///
/// # Design
///
/// The builder follows a composition approach:
/// - Uses existing `TypeDefBuilder` for the class definition
/// - Uses `FieldBuilder` for fields
/// - Uses `MethodBuilder` for methods and constructors
/// - Manages relationships between backing fields and properties
/// - Handles inheritance and interface implementations
///
/// # Examples
///
/// ## Simple Class
///
/// ```rust,no_run
/// use dotscope::prelude::*;
///
/// # fn example() -> dotscope::Result<()> {
/// # let view = CilAssemblyView::from_path("test.dll")?;
/// # let mut assembly = CilAssembly::new(view);
/// let class_token = ClassBuilder::new("Person")
///     .public()
///     .field("name", TypeSignature::String)
///     .field("age", TypeSignature::I4)
///     .default_constructor()
///     .build(&mut assembly)?;
/// # Ok(())
/// # }
/// ```
///
/// ## Class with Properties
///
/// ```rust,no_run
/// use dotscope::prelude::*;
/// use dotscope::metadata::signatures::TypeSignature;
///
/// # fn example() -> dotscope::Result<()> {
/// # let view = dotscope::CilAssemblyView::from_path("test.dll")?;
/// # let mut assembly = dotscope::CilAssembly::new(view);
/// let class_token = ClassBuilder::new("Employee")
///     .public()
///     .auto_property("Name", TypeSignature::String)
///     .auto_property("Salary", TypeSignature::R8)
///     .build(&mut assembly)?;
/// # Ok(())
/// # }
/// ```
///
/// ## Class with Custom Methods
///
/// ```rust,no_run
/// use dotscope::prelude::*;
/// use dotscope::metadata::signatures::TypeSignature;
///
/// # fn example() -> dotscope::Result<()> {
/// # let view = dotscope::CilAssemblyView::from_path("test.dll")?;
/// # let mut assembly = dotscope::CilAssembly::new(view);
/// let class_token = ClassBuilder::new("Calculator")
///     .public()
///     .field("lastResult", TypeSignature::I4)
///     .method(|_m| MethodBuilder::new("Add")
///         .public()
///         .parameter("a", TypeSignature::I4)
///         .parameter("b", TypeSignature::I4)
///         .returns(TypeSignature::I4)
///         .implementation(|body| {
///             body.implementation(|asm| {
///                 asm.ldarg_1()?
///                    .ldarg_2()?
///                    .add()?
///                    .dup()? // Duplicate for storing
///                    .ldarg_0()? // Load 'this'
///                    .stfld(Token::new(0x04000001))? // Store to lastResult (placeholder)
///                    .ret()?;
///                 Ok(())
///             })
///         }))
///     .build(&mut assembly)?;
/// # Ok(())
/// # }
/// ```
pub struct ClassBuilder {
    /// Class name
    name: String,

    /// Namespace (optional)
    namespace: Option<String>,

    /// Type attributes
    flags: u32,

    /// Base class token (defaults to System.Object)
    extends: Option<CodedIndex>,

    /// Implemented interfaces
    implements: Vec<CodedIndex>,

    /// Field definitions
    fields: Vec<FieldDefinition>,

    /// Method builders
    methods: Vec<MethodBuilder>,

    /// Property definitions
    properties: Vec<PropertyDefinition>,

    /// Whether to generate a default constructor
    generate_default_ctor: bool,

    /// Nested types (future enhancement)
    nested_types: Vec<ClassBuilder>,
}

impl ClassBuilder {
    /// Create a new class builder with the given name.
    ///
    /// # Arguments
    ///
    /// * `name` - Class name (without namespace)
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::prelude::*;
    ///
    /// let builder = ClassBuilder::new("MyClass");
    /// ```
    #[must_use]
    pub fn new(name: &str) -> Self {
        Self {
            name: name.to_string(),
            namespace: None,
            flags: 0x0010_0001, // CLASS | AUTO_LAYOUT | ANSI_CLASS
            extends: None,
            implements: Vec::new(),
            fields: Vec::new(),
            methods: Vec::new(),
            properties: Vec::new(),
            generate_default_ctor: false,
            nested_types: Vec::new(),
        }
    }

    /// Set the namespace for the class.
    ///
    /// # Arguments
    ///
    /// * `namespace` - Namespace (e.g., "System.Collections.Generic")
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::prelude::*;
    ///
    /// let builder = ClassBuilder::new("MyClass")
    ///     .namespace("MyCompany.MyProduct");
    /// ```
    #[must_use]
    pub fn namespace(mut self, namespace: &str) -> Self {
        self.namespace = Some(namespace.to_string());
        self
    }

    /// Make the class public.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::prelude::*;
    ///
    /// let builder = ClassBuilder::new("PublicClass").public();
    /// ```
    #[must_use]
    pub fn public(mut self) -> Self {
        self.flags = (self.flags & !0x0000_0007) | 0x0000_0001; // Clear visibility bits, set PUBLIC
        self
    }

    /// Make the class internal (not visible outside the assembly).
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::prelude::*;
    ///
    /// let builder = ClassBuilder::new("InternalClass").internal();
    /// ```
    #[must_use]
    pub fn internal(mut self) -> Self {
        self.flags &= !0x0000_0007; // Clear visibility bits, set NOT_PUBLIC (0)
        self
    }

    /// Make the class sealed (cannot be inherited).
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::prelude::*;
    ///
    /// let builder = ClassBuilder::new("SealedClass").sealed();
    /// ```
    #[must_use]
    pub fn sealed(mut self) -> Self {
        self.flags |= TypeAttributes::SEALED;
        self
    }

    /// Make the class abstract (cannot be instantiated).
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::prelude::*;
    ///
    /// let builder = ClassBuilder::new("AbstractClass").abstract_class();
    /// ```
    #[must_use]
    pub fn abstract_class(mut self) -> Self {
        self.flags |= TypeAttributes::ABSTRACT;
        self
    }

    /// Set the base class to inherit from.
    ///
    /// # Arguments
    ///
    /// * `base_class` - CodedIndex of the base class
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::prelude::*;
    /// use dotscope::metadata::tables::{CodedIndex, CodedIndexType, TableId};
    ///
    /// let builder = ClassBuilder::new("DerivedClass")
    ///     .inherits(CodedIndex::new(TableId::TypeRef, 1, CodedIndexType::TypeDefOrRef)); // Base class coded index
    /// ```
    #[must_use]
    pub fn inherits(mut self, base_class: CodedIndex) -> Self {
        self.extends = Some(base_class);
        self
    }

    /// Add an interface implementation.
    ///
    /// # Arguments
    ///
    /// * `interface` - CodedIndex of the interface to implement
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::prelude::*;
    /// use dotscope::metadata::tables::{CodedIndex, CodedIndexType, TableId};
    ///
    /// let builder = ClassBuilder::new("MyClass")
    ///     .implements(CodedIndex::new(TableId::TypeRef, 2, CodedIndexType::TypeDefOrRef)) // IDisposable
    ///     .implements(CodedIndex::new(TableId::TypeRef, 3, CodedIndexType::TypeDefOrRef)); // IEnumerable
    /// ```
    #[must_use]
    pub fn implements(mut self, interface: CodedIndex) -> Self {
        self.implements.push(interface);
        self
    }

    /// Add a field to the class.
    ///
    /// # Arguments
    ///
    /// * `name` - Field name
    /// * `field_type` - Field type
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::prelude::*;
    /// use dotscope::metadata::signatures::TypeSignature;
    ///
    /// let builder = ClassBuilder::new("Person")
    ///     .field("name", TypeSignature::String)
    ///     .field("age", TypeSignature::I4);
    /// ```
    #[must_use]
    pub fn field(mut self, name: &str, field_type: TypeSignature) -> Self {
        self.fields.push(FieldDefinition {
            name: name.to_string(),
            field_type,
            attributes: 0x0001, // PRIVATE
        });
        self
    }

    /// Add a public field to the class.
    ///
    /// # Arguments
    ///
    /// * `name` - Field name
    /// * `field_type` - Field type
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::prelude::*;
    /// use dotscope::metadata::signatures::TypeSignature;
    ///
    /// let builder = ClassBuilder::new("Point")
    ///     .public_field("X", TypeSignature::I4)
    ///     .public_field("Y", TypeSignature::I4);
    /// ```
    #[must_use]
    pub fn public_field(mut self, name: &str, field_type: TypeSignature) -> Self {
        self.fields.push(FieldDefinition {
            name: name.to_string(),
            field_type,
            attributes: 0x0006, // PUBLIC
        });
        self
    }

    /// Add a static field to the class.
    ///
    /// # Arguments
    ///
    /// * `name` - Field name
    /// * `field_type` - Field type
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::prelude::*;
    /// use dotscope::metadata::signatures::TypeSignature;
    ///
    /// let builder = ClassBuilder::new("Settings")
    ///     .static_field("instance", TypeSignature::Object);
    /// ```
    #[must_use]
    pub fn static_field(mut self, name: &str, field_type: TypeSignature) -> Self {
        self.fields.push(FieldDefinition {
            name: name.to_string(),
            field_type,
            attributes: 0x0001 | 0x0010, // PRIVATE | STATIC
        });
        self
    }

    /// Add a method to the class using a method builder.
    ///
    /// # Arguments
    ///
    /// * `builder_fn` - Function that configures a MethodBuilder
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::prelude::*;
    /// use dotscope::metadata::signatures::TypeSignature;
    ///
    /// # fn example() -> dotscope::Result<()> {
    /// # let view = dotscope::CilAssemblyView::from_path("test.dll")?;
    /// # let mut assembly = dotscope::CilAssembly::new(view);
    /// let class_token = ClassBuilder::new("Calculator")
    ///     .method(|_m| MethodBuilder::new("Add")
    ///         .public()
    ///         .parameter("a", TypeSignature::I4)
    ///         .parameter("b", TypeSignature::I4)
    ///         .returns(TypeSignature::I4)
    ///         .implementation(|body| {
    ///             body.implementation(|asm| {
    ///                 asm.ldarg_1()?.ldarg_2()?.add()?.ret()?;
    ///                 Ok(())
    ///             })
    ///         }))
    ///     .build(&mut assembly)?;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn method<F>(mut self, builder_fn: F) -> Self
    where
        F: FnOnce(MethodBuilder) -> MethodBuilder,
    {
        let method_builder = builder_fn(MethodBuilder::new("method"));
        self.methods.push(method_builder);
        self
    }

    /// Add an auto-property to the class.
    ///
    /// This creates a property with automatic backing field and getter/setter.
    ///
    /// # Arguments
    ///
    /// * `name` - Property name
    /// * `property_type` - Property type
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::prelude::*;
    /// use dotscope::metadata::signatures::TypeSignature;
    ///
    /// let builder = ClassBuilder::new("Person")
    ///     .auto_property("Name", TypeSignature::String)
    ///     .auto_property("Age", TypeSignature::I4);
    /// ```
    #[must_use]
    pub fn auto_property(mut self, name: &str, property_type: TypeSignature) -> Self {
        let backing_field_name = format!("<{name}>k__BackingField");

        // Add the property definition
        self.properties.push(PropertyDefinition {
            name: name.to_string(),
            property_type: property_type.clone(),
            has_getter: true,
            has_setter: true,
            backing_field_name: Some(backing_field_name.clone()),
        });

        // Add the backing field
        self.fields.push(FieldDefinition {
            name: backing_field_name,
            field_type: property_type,
            attributes: 0x0001, // PRIVATE | COMPILER_CONTROLLED (0x0000)
        });

        self
    }

    /// Add a read-only property to the class.
    ///
    /// # Arguments
    ///
    /// * `name` - Property name
    /// * `property_type` - Property type
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::prelude::*;
    /// use dotscope::metadata::signatures::TypeSignature;
    ///
    /// let builder = ClassBuilder::new("Circle")
    ///     .field("radius", TypeSignature::R8)
    ///     .readonly_property("Area", TypeSignature::R8);
    /// ```
    #[must_use]
    pub fn readonly_property(mut self, name: &str, property_type: TypeSignature) -> Self {
        let backing_field_name = format!("<{name}>k__BackingField");

        self.properties.push(PropertyDefinition {
            name: name.to_string(),
            property_type: property_type.clone(),
            has_getter: true,
            has_setter: false,
            backing_field_name: Some(backing_field_name.clone()),
        });

        self.fields.push(FieldDefinition {
            name: backing_field_name,
            field_type: property_type,
            attributes: 0x0001 | 0x0020, // PRIVATE | INIT_ONLY
        });

        self
    }

    /// Generate a default parameterless constructor.
    ///
    /// This will create a constructor that calls the base class constructor.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::prelude::*;
    ///
    /// let builder = ClassBuilder::new("MyClass")
    ///     .default_constructor();
    /// ```
    #[must_use]
    pub fn default_constructor(mut self) -> Self {
        self.generate_default_ctor = true;
        self
    }

    /// Build the complete class and add it to the assembly.
    ///
    /// This method orchestrates the creation of:
    /// 1. TypeDef table entry for the class
    /// 2. Field table entries for all fields
    /// 3. Method table entries for all methods and property accessors
    /// 4. Property table entries (future enhancement)
    /// 5. InterfaceImpl table entries for implemented interfaces
    ///
    /// # Arguments
    ///
    /// * `assembly` - CilAssembly for managing the assembly
    ///
    /// # Returns
    ///
    /// A token representing the newly created class definition.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Class creation fails at any step
    /// - Both sealed and abstract flags are set (mutually exclusive per ECMA-335)
    pub fn build(self, assembly: &mut CilAssembly) -> Result<ChangeRefRc> {
        // Validate that sealed and abstract are not both set (mutually exclusive)
        if (self.flags & TypeAttributes::SEALED) != 0
            && (self.flags & TypeAttributes::ABSTRACT) != 0
        {
            return Err(Error::ModificationInvalid(
                "Class cannot be both sealed and abstract (mutually exclusive flags per ECMA-335)"
                    .to_string(),
            ));
        }

        // Create the TypeDef entry
        let typedef_ref = TypeDefBuilder::new()
            .name(&self.name)
            .namespace(self.namespace.as_deref().unwrap_or(""))
            .flags(self.flags)
            .extends(
                self.extends
                    .unwrap_or_else(|| CodedIndex::null(CodedIndexType::TypeDefOrRef)),
            ) // null = no base class (will default to Object)
            .build(assembly)?;

        // Create field definitions and store their change refs
        let mut field_refs: Vec<(String, ChangeRefRc)> = Vec::new();
        for field_def in &self.fields {
            // Encode the field signature
            let field_sig = SignatureField {
                modifiers: Vec::new(),
                base: field_def.field_type.clone(),
            };
            let sig_bytes = encode_field_signature(&field_sig)?;

            let field_ref = FieldBuilder::new()
                .name(&field_def.name)
                .flags(field_def.attributes)
                .signature(&sig_bytes)
                .build(assembly)?;
            field_refs.push((field_def.name.clone(), field_ref));
        }

        // Generate default constructor if requested
        if self.generate_default_ctor {
            let base_ctor_token = Token::new(0x0A00_0001); // Placeholder for Object::.ctor

            MethodBuilder::constructor()
                .implementation(move |body| {
                    body.implementation(move |asm| {
                        asm.ldarg_0()? // Load 'this'
                            .call(base_ctor_token)? // Call base constructor
                            .ret()?;
                        Ok(())
                    })
                })
                .build(assembly)?;
        }

        // Create property getter/setter methods
        for prop_def in &self.properties {
            if let Some(backing_field_name) = &prop_def.backing_field_name {
                // Find the backing field change ref and get its placeholder token
                let backing_field_ref = field_refs
                    .iter()
                    .find(|(name, _)| name == backing_field_name)
                    .map(|(_, change_ref)| change_ref.clone())
                    .ok_or_else(|| {
                        Error::ModificationInvalid(format!(
                            "Backing field {backing_field_name} not found"
                        ))
                    })?;

                let backing_field_token =
                    backing_field_ref.placeholder_token().ok_or_else(|| {
                        Error::ModificationInvalid(
                            "Failed to get placeholder token for backing field".to_string(),
                        )
                    })?;

                // Create getter
                if prop_def.has_getter {
                    let getter_field_token = backing_field_token; // Copy token for move
                    MethodBuilder::property_getter(&prop_def.name, prop_def.property_type.clone())
                        .implementation(move |body| {
                            body.implementation(move |asm| {
                                asm.ldarg_0()? // Load 'this'
                                    .ldfld(getter_field_token)? // Load field
                                    .ret()?;
                                Ok(())
                            })
                        })
                        .build(assembly)?;
                }

                // Create setter
                if prop_def.has_setter {
                    let setter_field_token = backing_field_token; // Copy token for move
                    MethodBuilder::property_setter(&prop_def.name, prop_def.property_type.clone())
                        .implementation(move |body| {
                            body.implementation(move |asm| {
                                asm.ldarg_0()? // Load 'this'
                                    .ldarg_1()? // Load value
                                    .stfld(setter_field_token)? // Store to field
                                    .ret()?;
                                Ok(())
                            })
                        })
                        .build(assembly)?;
                }
            }
        }

        // Build custom methods
        for method_builder in self.methods {
            method_builder.build(assembly)?;
        }

        // Create InterfaceImpl entries - use placeholder for the class reference
        for interface_index in self.implements {
            InterfaceImplBuilder::new()
                .class(typedef_ref.placeholder())
                .interface(interface_index)
                .build(assembly)?;
        }

        Ok(typedef_ref)
    }
}

impl Default for ClassBuilder {
    fn default() -> Self {
        Self::new("DefaultClass")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        cilassembly::{changes::ChangeRefKind, CilAssembly},
        metadata::{cilassemblyview::CilAssemblyView, signatures::TypeSignature, tables::TableId},
    };
    use std::path::PathBuf;

    fn get_test_assembly() -> Result<CilAssembly> {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        let view = CilAssemblyView::from_path(&path)?;
        Ok(CilAssembly::new(view))
    }

    #[test]
    fn test_simple_class() -> Result<()> {
        let mut assembly = get_test_assembly()?;

        let class_ref = ClassBuilder::new("SimpleClass")
            .public()
            .field("value", TypeSignature::I4)
            .default_constructor()
            .build(&mut assembly)?;

        // Should create a valid TypeDef reference
        assert_eq!(class_ref.kind(), ChangeRefKind::TableRow(TableId::TypeDef));

        Ok(())
    }

    #[test]
    fn test_class_with_namespace() -> Result<()> {
        let mut assembly = get_test_assembly()?;

        let class_ref = ClassBuilder::new("MyClass")
            .namespace("MyCompany.MyProduct")
            .public()
            .build(&mut assembly)?;

        assert_eq!(class_ref.kind(), ChangeRefKind::TableRow(TableId::TypeDef));

        Ok(())
    }

    #[test]
    fn test_class_with_auto_properties() -> Result<()> {
        let mut assembly = get_test_assembly()?;

        let class_ref = ClassBuilder::new("Person")
            .public()
            .auto_property("Name", TypeSignature::String)
            .auto_property("Age", TypeSignature::I4)
            .default_constructor()
            .build(&mut assembly)?;

        assert_eq!(class_ref.kind(), ChangeRefKind::TableRow(TableId::TypeDef));

        Ok(())
    }

    #[test]
    fn test_class_with_methods() -> Result<()> {
        let mut assembly = get_test_assembly()?;

        let class_ref = ClassBuilder::new("Calculator")
            .public()
            .field("lastResult", TypeSignature::I4)
            .method(|_m| {
                MethodBuilder::new("Add")
                    .public()
                    .static_method()
                    .parameter("a", TypeSignature::I4)
                    .parameter("b", TypeSignature::I4)
                    .returns(TypeSignature::I4)
                    .implementation(|body| {
                        body.implementation(|asm| {
                            asm.ldarg_0()?.ldarg_1()?.add()?.ret()?;
                            Ok(())
                        })
                    })
            })
            .build(&mut assembly)?;

        assert_eq!(class_ref.kind(), ChangeRefKind::TableRow(TableId::TypeDef));

        Ok(())
    }

    #[test]
    fn test_sealed_class() -> Result<()> {
        let mut assembly = get_test_assembly()?;

        let class_ref = ClassBuilder::new("SealedClass")
            .public()
            .sealed()
            .build(&mut assembly)?;

        assert_eq!(class_ref.kind(), ChangeRefKind::TableRow(TableId::TypeDef));

        Ok(())
    }

    #[test]
    fn test_abstract_class() -> Result<()> {
        let mut assembly = get_test_assembly()?;

        let class_ref = ClassBuilder::new("AbstractBase")
            .public()
            .abstract_class()
            .build(&mut assembly)?;

        assert_eq!(class_ref.kind(), ChangeRefKind::TableRow(TableId::TypeDef));

        Ok(())
    }

    #[test]
    fn test_class_with_static_fields() -> Result<()> {
        let mut assembly = get_test_assembly()?;

        let class_ref = ClassBuilder::new("Configuration")
            .public()
            .static_field("instance", TypeSignature::Object)
            .public_field("settings", TypeSignature::String)
            .build(&mut assembly)?;

        assert_eq!(class_ref.kind(), ChangeRefKind::TableRow(TableId::TypeDef));

        Ok(())
    }

    #[test]
    fn test_class_with_readonly_property() -> Result<()> {
        let mut assembly = get_test_assembly()?;

        let class_ref = ClassBuilder::new("Circle")
            .public()
            .field("radius", TypeSignature::R8)
            .readonly_property("Diameter", TypeSignature::R8)
            .default_constructor()
            .build(&mut assembly)?;

        assert_eq!(class_ref.kind(), ChangeRefKind::TableRow(TableId::TypeDef));

        Ok(())
    }

    #[test]
    fn test_class_with_inheritance() -> Result<()> {
        let mut assembly = get_test_assembly()?;

        let base_class_index = CodedIndex::new(TableId::TypeRef, 1, CodedIndexType::TypeDefOrRef); // Placeholder base class

        let class_ref = ClassBuilder::new("DerivedClass")
            .public()
            .inherits(base_class_index)
            .default_constructor()
            .build(&mut assembly)?;

        assert_eq!(class_ref.kind(), ChangeRefKind::TableRow(TableId::TypeDef));

        Ok(())
    }

    #[test]
    fn test_class_with_interfaces() -> Result<()> {
        let mut assembly = get_test_assembly()?;

        let interface1 = CodedIndex::new(TableId::TypeRef, 2, CodedIndexType::TypeDefOrRef); // Placeholder interface
        let interface2 = CodedIndex::new(TableId::TypeRef, 3, CodedIndexType::TypeDefOrRef); // Another interface

        let class_ref = ClassBuilder::new("Implementation")
            .public()
            .implements(interface1)
            .implements(interface2)
            .build(&mut assembly)?;

        assert_eq!(class_ref.kind(), ChangeRefKind::TableRow(TableId::TypeDef));

        Ok(())
    }

    #[test]
    fn test_sealed_and_abstract_mutually_exclusive() {
        let mut assembly = get_test_assembly().unwrap();

        // Attempting to create a class that is both sealed and abstract should fail
        let result = ClassBuilder::new("InvalidClass")
            .public()
            .sealed()
            .abstract_class()
            .build(&mut assembly);

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("sealed and abstract"),
            "Error should mention sealed and abstract conflict: {}",
            err
        );
    }
}