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
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
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
//! High-level property builder for creating .NET property definitions.
//!
//! This module provides [`PropertyBuilder`] for creating complete property definitions
//! including backing fields, getter/setter methods, and property metadata. It orchestrates
//! the existing low-level builders to provide a fluent, high-level API for various property patterns.

use crate::{
    cilassembly::{ChangeRefRc, CilAssembly},
    metadata::{
        signatures::{
            encode_field_signature, encode_property_signature, SignatureField, SignatureParameter,
            SignatureProperty, TypeSignature,
        },
        tables::{FieldBuilder, PropertyBuilder as PropertyTableBuilder},
    },
    Error, Result,
};

use super::method::MethodBuilder;

/// Property accessor type for determining what accessors to generate.
#[derive(Debug, Clone, PartialEq)]
pub enum PropertyAccessors {
    /// Property has both getter and setter
    GetterAndSetter,
    /// Property has only a getter (read-only)
    GetterOnly,
    /// Property has only a setter (write-only, rare)
    SetterOnly,
    /// No automatic accessors (custom implementation required)
    None,
}

/// Property implementation strategy.
pub enum PropertyImplementation {
    /// Auto-property with automatic backing field
    Auto {
        /// Name of the backing field (auto-generated if None)
        backing_field_name: Option<String>,
        /// Backing field attributes
        backing_field_attributes: u32,
    },
    /// Computed property with custom getter/setter logic
    Computed {
        /// Custom getter implementation
        getter: Option<Box<dyn FnOnce(MethodBuilder) -> MethodBuilder + Send>>,
        /// Custom setter implementation  
        setter: Option<Box<dyn FnOnce(MethodBuilder) -> MethodBuilder + Send>>,
    },
    /// Manual implementation (user provides all methods separately)
    Manual,
}

/// High-level builder for creating complete property definitions.
///
/// `PropertyBuilder` provides a fluent API for creating properties with various patterns:
/// auto-properties, computed properties, indexed properties, and custom implementations.
/// It composes the existing low-level builders to provide convenient high-level interfaces.
///
/// # Design
///
/// The builder supports multiple property patterns:
/// - **Auto-properties**: Automatic backing fields with generated getters/setters
/// - **Computed properties**: Custom logic without backing fields
/// - **Read-only/Write-only**: Properties with only getter or setter
/// - **Indexed properties**: Properties with parameters (C# indexers)
/// - **Manual**: Complete custom control over implementation
///
/// # Examples
///
/// ## Simple Auto-Property
///
/// ```rust,no_run
/// use dotscope::prelude::*;
///
/// # fn example() -> dotscope::Result<()> {
/// # let view = CilAssemblyView::from_path("test.dll")?;
/// # let mut assembly = CilAssembly::new(view);
/// let property_token = PropertyBuilder::new("Name", TypeSignature::String)
///     .auto_property()
///     .public_accessors()
///     .build(&mut assembly)?;
/// # Ok(())
/// # }
/// ```
///
/// ## Read-Only Computed Property
///
/// ```rust,no_run
/// use dotscope::prelude::*;
///
/// # fn example() -> dotscope::Result<()> {
/// # let view = CilAssemblyView::from_path("test.dll")?;
/// # let mut assembly = CilAssembly::new(view);
/// let property_token = PropertyBuilder::new("FullName", TypeSignature::String)
///     .computed()
///     .getter(|method| method
///         .implementation(|body| {
///             body.implementation(|asm| {
///                 // Custom logic to compute full name
///                 asm.ldstr(Token::new(0x70000001))? // "Computed Value"
///                    .ret()?;
///                 Ok(())
///             })
///         }))
///     .readonly()
///     .build(&mut assembly)?;
/// # Ok(())
/// # }
/// ```
///
/// ## Property with Custom Backing Field
///
/// ```rust,no_run
/// use dotscope::prelude::*;
///
/// # fn example() -> dotscope::Result<()> {
/// # let view = CilAssemblyView::from_path("test.dll")?;
/// # let mut assembly = CilAssembly::new(view);
/// let property_token = PropertyBuilder::new("Value", TypeSignature::I4)
///     .auto_property()
///     .backing_field("_customValue")
///     .private_backing_field()
///     .public_accessors()
///     .build(&mut assembly)?;
/// # Ok(())
/// # }
/// ```
pub struct PropertyBuilder {
    /// Property name
    name: String,

    /// Property type
    property_type: TypeSignature,

    /// Property attributes
    attributes: u32,

    /// What accessors to generate
    accessors: PropertyAccessors,

    /// Accessor visibility (separate from property attributes)
    getter_attributes: u32,
    setter_attributes: u32,

    /// Implementation strategy
    implementation: PropertyImplementation,

    /// Whether this is an indexed property (has parameters)
    is_indexed: bool,

    /// Parameters for indexed properties
    parameters: Vec<(String, TypeSignature)>,
}

impl PropertyBuilder {
    /// Create a new property builder with the given name and type.
    ///
    /// # Arguments
    ///
    /// * `name` - Property name
    /// * `property_type` - Property type signature
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::prelude::*;
    ///
    /// let builder = PropertyBuilder::new("Name", TypeSignature::String);
    /// ```
    #[must_use]
    pub fn new(name: &str, property_type: TypeSignature) -> Self {
        Self {
            name: name.to_string(),
            property_type,
            attributes: 0x0000, // Default property attributes
            accessors: PropertyAccessors::GetterAndSetter,
            getter_attributes: 0x0006, // PUBLIC
            setter_attributes: 0x0006, // PUBLIC
            implementation: PropertyImplementation::Auto {
                backing_field_name: None,
                backing_field_attributes: 0x0001, // PRIVATE
            },
            is_indexed: false,
            parameters: Vec::new(),
        }
    }

    /// Configure this as an auto-property with automatic backing field.
    ///
    /// This is the default behavior and creates a property similar to C# auto-properties.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::prelude::*;
    ///
    /// let builder = PropertyBuilder::new("Name", TypeSignature::String)
    ///     .auto_property();
    /// ```
    #[must_use]
    pub fn auto_property(mut self) -> Self {
        self.implementation = PropertyImplementation::Auto {
            backing_field_name: None,
            backing_field_attributes: 0x0001, // PRIVATE
        };
        self
    }

    /// Configure this as a computed property with custom logic.
    ///
    /// Computed properties don't have backing fields and require custom getter/setter implementations.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::prelude::*;
    ///
    /// let builder = PropertyBuilder::new("Area", TypeSignature::R8)
    ///     .computed();
    /// ```
    #[must_use]
    pub fn computed(mut self) -> Self {
        self.implementation = PropertyImplementation::Computed {
            getter: None,
            setter: None,
        };
        self
    }

    /// Configure this as a manual property where all methods are provided separately.
    ///
    /// Manual properties give complete control but require the user to provide all implementations.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::prelude::*;
    ///
    /// let builder = PropertyBuilder::new("Complex", TypeSignature::Object)
    ///     .manual();
    /// ```
    #[must_use]
    pub fn manual(mut self) -> Self {
        self.implementation = PropertyImplementation::Manual;
        self
    }

    /// Set a custom name for the backing field (auto-properties only).
    ///
    /// # Arguments
    ///
    /// * `field_name` - Custom backing field name
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::prelude::*;
    ///
    /// let builder = PropertyBuilder::new("Value", TypeSignature::I4)
    ///     .backing_field("_value");
    /// ```
    #[must_use]
    pub fn backing_field(mut self, field_name: &str) -> Self {
        if let PropertyImplementation::Auto {
            backing_field_name, ..
        } = &mut self.implementation
        {
            *backing_field_name = Some(field_name.to_string());
        }
        self
    }

    /// Make the backing field private (default for auto-properties).
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::prelude::*;
    ///
    /// let builder = PropertyBuilder::new("Value", TypeSignature::I4)
    ///     .private_backing_field();
    /// ```
    #[must_use]
    pub fn private_backing_field(mut self) -> Self {
        if let PropertyImplementation::Auto {
            backing_field_attributes,
            ..
        } = &mut self.implementation
        {
            *backing_field_attributes = 0x0001; // PRIVATE
        }
        self
    }

    /// Make the backing field public (unusual but possible).
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::prelude::*;
    ///
    /// let builder = PropertyBuilder::new("Value", TypeSignature::I4)
    ///     .public_backing_field();
    /// ```
    #[must_use]
    pub fn public_backing_field(mut self) -> Self {
        if let PropertyImplementation::Auto {
            backing_field_attributes,
            ..
        } = &mut self.implementation
        {
            *backing_field_attributes = 0x0006; // PUBLIC
        }
        self
    }

    /// Make this a read-only property (getter only).
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::prelude::*;
    ///
    /// let builder = PropertyBuilder::new("ReadOnlyValue", TypeSignature::I4)
    ///     .readonly();
    /// ```
    #[must_use]
    pub fn readonly(mut self) -> Self {
        self.accessors = PropertyAccessors::GetterOnly;
        self
    }

    /// Make this a write-only property (setter only, rare).
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::prelude::*;
    ///
    /// let builder = PropertyBuilder::new("WriteOnlyValue", TypeSignature::I4)
    ///     .writeonly();
    /// ```
    #[must_use]
    pub fn writeonly(mut self) -> Self {
        self.accessors = PropertyAccessors::SetterOnly;
        self
    }

    /// Configure both getter and setter accessors (default).
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::prelude::*;
    ///
    /// let builder = PropertyBuilder::new("Value", TypeSignature::I4)
    ///     .getter_and_setter();
    /// ```
    #[must_use]
    pub fn getter_and_setter(mut self) -> Self {
        self.accessors = PropertyAccessors::GetterAndSetter;
        self
    }

    /// Make both accessors public.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::prelude::*;
    ///
    /// let builder = PropertyBuilder::new("Value", TypeSignature::I4)
    ///     .public_accessors();
    /// ```
    #[must_use]
    pub fn public_accessors(mut self) -> Self {
        self.getter_attributes = 0x0006; // PUBLIC
        self.setter_attributes = 0x0006; // PUBLIC
        self
    }

    /// Make both accessors private.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::prelude::*;
    ///
    /// let builder = PropertyBuilder::new("Value", TypeSignature::I4)
    ///     .private_accessors();
    /// ```
    #[must_use]
    pub fn private_accessors(mut self) -> Self {
        self.getter_attributes = 0x0001; // PRIVATE
        self.setter_attributes = 0x0001; // PRIVATE
        self
    }

    /// Set getter visibility separately.
    ///
    /// # Arguments
    ///
    /// * `attributes` - Method attributes for the getter
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::prelude::*;
    ///
    /// let builder = PropertyBuilder::new("Value", TypeSignature::I4)
    ///     .getter_visibility(0x0006); // PUBLIC
    /// ```
    #[must_use]
    pub fn getter_visibility(mut self, attributes: u32) -> Self {
        self.getter_attributes = attributes;
        self
    }

    /// Set setter visibility separately.
    ///
    /// # Arguments
    ///
    /// * `attributes` - Method attributes for the setter
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::prelude::*;
    ///
    /// let builder = PropertyBuilder::new("Value", TypeSignature::I4)
    ///     .setter_visibility(0x0001); // PRIVATE
    /// ```
    #[must_use]
    pub fn setter_visibility(mut self, attributes: u32) -> Self {
        self.setter_attributes = attributes;
        self
    }

    /// Add a custom getter implementation (for computed properties).
    ///
    /// # Arguments
    ///
    /// * `implementation` - Function that configures the getter method
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::prelude::*;
    ///
    /// # fn example() -> dotscope::Result<()> {
    /// # let view = CilAssemblyView::from_path("test.dll")?;
    /// # let mut assembly = CilAssembly::new(view);
    /// let builder = PropertyBuilder::new("ComputedValue", TypeSignature::I4)
    ///     .computed()
    ///     .getter(|method| method
    ///         .implementation(|body| {
    ///             body.implementation(|asm| {
    ///                 asm.ldc_i4(42)?.ret()?;
    ///                 Ok(())
    ///             })
    ///         }));
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn getter<F>(mut self, implementation: F) -> Self
    where
        F: FnOnce(MethodBuilder) -> MethodBuilder + Send + 'static,
    {
        if let PropertyImplementation::Computed { getter, .. } = &mut self.implementation {
            *getter = Some(Box::new(implementation));
        }
        self
    }

    /// Add a custom setter implementation (for computed properties).
    ///
    /// # Arguments
    ///
    /// * `implementation` - Function that configures the setter method
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::prelude::*;
    ///
    /// # fn example() -> dotscope::Result<()> {
    /// # let view = CilAssemblyView::from_path("test.dll")?;
    /// # let mut assembly = CilAssembly::new(view);
    /// let builder = PropertyBuilder::new("ComputedValue", TypeSignature::I4)
    ///     .computed()
    ///     .setter(|method| method
    ///         .implementation(|body| {
    ///             body.implementation(|asm| {
    ///                 // Custom setter logic
    ///                 asm.ret()?;
    ///                 Ok(())
    ///             })
    ///         }));
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn setter<F>(mut self, implementation: F) -> Self
    where
        F: FnOnce(MethodBuilder) -> MethodBuilder + Send + 'static,
    {
        if let PropertyImplementation::Computed { setter, .. } = &mut self.implementation {
            *setter = Some(Box::new(implementation));
        }
        self
    }

    /// Make this an indexed property with parameters.
    ///
    /// Indexed properties are like C# indexers and take parameters.
    ///
    /// # Arguments
    ///
    /// * `param_name` - Parameter name
    /// * `param_type` - Parameter type
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::prelude::*;
    ///
    /// let builder = PropertyBuilder::new("Item", TypeSignature::String)
    ///     .indexed("index", TypeSignature::I4);
    /// ```
    #[must_use]
    pub fn indexed(mut self, param_name: &str, param_type: TypeSignature) -> Self {
        self.is_indexed = true;
        self.parameters.push((param_name.to_string(), param_type));
        self
    }

    /// Add additional parameters to an indexed property.
    ///
    /// # Arguments
    ///
    /// * `param_name` - Parameter name  
    /// * `param_type` - Parameter type
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::prelude::*;
    ///
    /// let builder = PropertyBuilder::new("Item", TypeSignature::String)
    ///     .indexed("row", TypeSignature::I4)
    ///     .parameter("column", TypeSignature::I4);
    /// ```
    #[must_use]
    pub fn parameter(mut self, param_name: &str, param_type: TypeSignature) -> Self {
        self.parameters.push((param_name.to_string(), param_type));
        self
    }

    /// Set property attributes.
    ///
    /// # Arguments
    ///
    /// * `attributes` - Property attributes bitmask
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::prelude::*;
    ///
    /// let builder = PropertyBuilder::new("Value", TypeSignature::I4)
    ///     .attributes(0x0200); // SPECIAL_NAME
    /// ```
    #[must_use]
    pub fn attributes(mut self, attributes: u32) -> Self {
        self.attributes = attributes;
        self
    }

    /// Build the complete property and add it to the assembly.
    ///
    /// This method orchestrates the creation of:
    /// 1. Property table entry
    /// 2. Backing field (for auto-properties)
    /// 3. Getter method (if applicable)
    /// 4. Setter method (if applicable)
    /// 5. PropertyMap entry linking property to parent type
    ///
    /// # Arguments
    ///
    /// * `assembly` - CIL assembly for managing the metadata
    ///
    /// # Returns
    ///
    /// A token representing the newly created property definition.
    ///
    /// # Errors
    ///
    /// Returns an error if property creation fails at any step.
    pub fn build(self, assembly: &mut CilAssembly) -> Result<ChangeRefRc> {
        // Create property signature with parameters for indexed properties
        let mut signature_params = Vec::new();
        for (_param_name, param_type) in &self.parameters {
            signature_params.push(SignatureParameter {
                modifiers: Vec::new(),
                by_ref: false,
                base: param_type.clone(),
            });
        }

        let property_signature = SignatureProperty {
            has_this: true, // Most properties are instance properties
            modifiers: Vec::new(),
            base: self.property_type.clone(),
            params: signature_params,
        };

        // Encode property signature to bytes
        let signature_bytes = encode_property_signature(&property_signature)?;

        // Create the property table entry
        let property_ref = PropertyTableBuilder::new()
            .name(&self.name)
            .flags(self.attributes)
            .signature(&signature_bytes)
            .build(assembly)?;

        // Handle different implementation strategies
        match self.implementation {
            PropertyImplementation::Auto {
                backing_field_name,
                backing_field_attributes,
            } => {
                // Generate backing field name if not provided
                let field_name =
                    backing_field_name.unwrap_or_else(|| format!("<{}>k__BackingField", self.name));

                // Create backing field
                let field_sig = SignatureField {
                    modifiers: Vec::new(),
                    base: self.property_type.clone(),
                };
                let sig_bytes = encode_field_signature(&field_sig)?;

                let backing_field_ref = FieldBuilder::new()
                    .name(&field_name)
                    .flags(backing_field_attributes)
                    .signature(&sig_bytes)
                    .build(assembly)?;

                // Get the placeholder token for use in IL instructions
                let backing_field_placeholder =
                    backing_field_ref.placeholder_token().ok_or_else(|| {
                        Error::ModificationInvalid(
                            "Failed to get placeholder token for backing field".to_string(),
                        )
                    })?;

                // Create getter if needed
                if matches!(
                    self.accessors,
                    PropertyAccessors::GetterAndSetter | PropertyAccessors::GetterOnly
                ) {
                    let getter_field_token = backing_field_placeholder; // Copy for move
                    let getter_name = self.name.clone();
                    let getter_type = self.property_type.clone();
                    let getter_visibility = self.getter_attributes;

                    let getter = MethodBuilder::property_getter(&getter_name, getter_type);
                    let getter = match getter_visibility {
                        0x0001 => getter.private(),
                        _ => getter.public(),
                    };

                    getter
                        .implementation(move |body| {
                            body.implementation(move |asm| {
                                asm.ldarg_0()? // Load 'this'
                                    .ldfld(getter_field_token)? // Load backing field
                                    .ret()?;
                                Ok(())
                            })
                        })
                        .build(assembly)?;
                }

                // Create setter if needed
                if matches!(
                    self.accessors,
                    PropertyAccessors::GetterAndSetter | PropertyAccessors::SetterOnly
                ) {
                    let setter_field_token = backing_field_placeholder; // Copy for move
                    let setter_name = self.name.clone();
                    let setter_type = self.property_type.clone();
                    let setter_visibility = self.setter_attributes;

                    let setter = MethodBuilder::property_setter(&setter_name, setter_type);
                    let setter = match setter_visibility {
                        0x0001 => setter.private(),
                        _ => setter.public(),
                    };

                    setter
                        .implementation(move |body| {
                            body.implementation(move |asm| {
                                asm.ldarg_0()? // Load 'this'
                                    .ldarg_1()? // Load value
                                    .stfld(setter_field_token)? // Store to backing field
                                    .ret()?;
                                Ok(())
                            })
                        })
                        .build(assembly)?;
                }

                Ok(property_ref)
            }
            PropertyImplementation::Computed { getter, setter } => {
                // Create getter if provided and needed
                if matches!(
                    self.accessors,
                    PropertyAccessors::GetterAndSetter | PropertyAccessors::GetterOnly
                ) {
                    if let Some(getter_impl) = getter {
                        let getter_method =
                            MethodBuilder::property_getter(&self.name, self.property_type.clone());
                        let getter_method = match self.getter_attributes {
                            0x0001 => getter_method.private(),
                            _ => getter_method.public(),
                        };

                        let configured_getter = getter_impl(getter_method);
                        configured_getter.build(assembly)?;
                    } else {
                        return Err(Error::ModificationInvalid(
                            "Computed property requires getter implementation".to_string(),
                        ));
                    }
                }

                // Create setter if provided and needed
                if matches!(
                    self.accessors,
                    PropertyAccessors::GetterAndSetter | PropertyAccessors::SetterOnly
                ) {
                    if let Some(setter_impl) = setter {
                        let setter_method =
                            MethodBuilder::property_setter(&self.name, self.property_type.clone());
                        let setter_method = match self.setter_attributes {
                            0x0001 => setter_method.private(),
                            _ => setter_method.public(),
                        };

                        let configured_setter = setter_impl(setter_method);
                        configured_setter.build(assembly)?;
                    } else {
                        return Err(Error::ModificationInvalid(
                            "Computed property requires setter implementation".to_string(),
                        ));
                    }
                }

                Ok(property_ref)
            }
            PropertyImplementation::Manual => {
                // For manual implementation, just return the property reference
                // User is responsible for creating methods separately
                Ok(property_ref)
            }
        }
    }
}

impl Default for PropertyBuilder {
    fn default() -> Self {
        Self::new("DefaultProperty", TypeSignature::Object)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        cilassembly::{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_auto_property() -> Result<()> {
        let mut assembly = get_test_assembly()?;

        let property_ref = PropertyBuilder::new("Name", TypeSignature::String)
            .auto_property()
            .public_accessors()
            .build(&mut assembly)?;

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

        Ok(())
    }

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

        let property_ref = PropertyBuilder::new("ReadOnlyValue", TypeSignature::I4)
            .auto_property()
            .readonly()
            .public_accessors()
            .build(&mut assembly)?;

        assert_eq!(
            property_ref.kind(),
            ChangeRefKind::TableRow(TableId::Property)
        );

        Ok(())
    }

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

        let property_ref = PropertyBuilder::new("ComputedValue", TypeSignature::I4)
            .computed()
            .getter(|method| {
                method.implementation(|body| {
                    body.implementation(|asm| {
                        asm.ldc_i4(42)?.ret()?;
                        Ok(())
                    })
                })
            })
            .readonly()
            .build(&mut assembly)?;

        assert_eq!(
            property_ref.kind(),
            ChangeRefKind::TableRow(TableId::Property)
        );

        Ok(())
    }

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

        let property_ref = PropertyBuilder::new("Value", TypeSignature::R8)
            .auto_property()
            .backing_field("_customValue")
            .private_backing_field()
            .public_accessors()
            .build(&mut assembly)?;

        assert_eq!(
            property_ref.kind(),
            ChangeRefKind::TableRow(TableId::Property)
        );

        Ok(())
    }

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

        let property_ref = PropertyBuilder::new("Item", TypeSignature::String)
            .auto_property()
            .indexed("index", TypeSignature::I4)
            .public_accessors()
            .build(&mut assembly)?;

        assert_eq!(
            property_ref.kind(),
            ChangeRefKind::TableRow(TableId::Property)
        );

        Ok(())
    }

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

        let property_ref = PropertyBuilder::new("Matrix", TypeSignature::I4)
            .auto_property()
            .indexed("row", TypeSignature::I4)
            .parameter("column", TypeSignature::I4)
            .public_accessors()
            .build(&mut assembly)?;

        assert_eq!(
            property_ref.kind(),
            ChangeRefKind::TableRow(TableId::Property)
        );

        Ok(())
    }

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

        let property_ref = PropertyBuilder::new("WriteOnly", TypeSignature::String)
            .auto_property()
            .writeonly()
            .public_accessors()
            .build(&mut assembly)?;

        assert_eq!(
            property_ref.kind(),
            ChangeRefKind::TableRow(TableId::Property)
        );

        Ok(())
    }

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

        let property_ref = PropertyBuilder::new("Manual", TypeSignature::Object)
            .manual()
            .build(&mut assembly)?;

        assert_eq!(
            property_ref.kind(),
            ChangeRefKind::TableRow(TableId::Property)
        );

        Ok(())
    }

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

        let property_ref = PropertyBuilder::new("MixedVisibility", TypeSignature::I4)
            .auto_property()
            .getter_visibility(0x0006) // PUBLIC
            .setter_visibility(0x0001) // PRIVATE
            .build(&mut assembly)?;

        assert_eq!(
            property_ref.kind(),
            ChangeRefKind::TableRow(TableId::Property)
        );

        Ok(())
    }

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

        let result = PropertyBuilder::new("InvalidComputed", TypeSignature::I4)
            .computed()
            .readonly()
            .build(&mut assembly);

        assert!(result.is_err());
    }

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

        let result = PropertyBuilder::new("InvalidComputed", TypeSignature::I4)
            .computed()
            .writeonly()
            .build(&mut assembly);

        assert!(result.is_err());
    }
}