hao 0.0.19

Read, edit, create and write .net assemblies
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
//! Type and method signatures (ECMA-335 II.23.2).
//!
//! A [`TypeSig`] is a type as used by a member: `int`, `string[]`,
//! `List<T>`, `ref Point`. A [`MethodSig`] is a method's return and parameter
//! types plus its calling convention, and [`FieldSig`]/[`PropertySig`] the
//! same for fields and properties. They are decoded from (and encoded back to)
//! the metadata's signature blobs when a module is loaded and written.
//!
//! Built-in types are constants or [`PrimitiveType`]s; named types are
//! [`TypeDefOrRef`] handles from the module the signature is used in:
//!
//! ```
//! use hao::dotnet::entries::well_known::SystemCollectionsGenericType;
//! use hao::prelude::*;
//!
//! let mut module = Module::new("Demo", ModuleKind::Dll, TargetRuntime::NetCore(9));
//! let list = module.corlib_type(SystemCollectionsGenericType::List_1).unwrap();
//!
//! // static List<string> Split(string text, char[] separators)
//! let sig = MethodSig::new_static(
//!     TypeSig::generic_class(list, vec![TypeSig::STRING]),
//!     vec![TypeSig::STRING, TypeSig::sz_array(TypeSig::CHAR)],
//! );
//! assert_eq!(sig.params.len(), 2);
//! ```

mod reader;
mod writer;

pub(crate) use reader::{decode_compressed_u32, SignatureReader, StandAloneSig, TokenResolver};
pub(crate) use writer::{encode_compressed_u32, SignatureWriter, TokenEncoder};

use bitflags::bitflags;
use strum::{EnumString, FromRepr, IntoStaticStr};

use crate::dotnet::entries::TypeDefOrRef;

/// An `ELEMENT_TYPE_*` byte: the tag at the start of each type in a signature
/// blob (ECMA-335 II.23.1.16).
///
/// This is the raw encoding; parsed signatures use [`TypeSig`] instead.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, FromRepr)]
#[repr(u8)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub enum ElementType {
    /// Marks the end of a list; not a type.
    End = 0x00,
    /// `void`.
    Void = 0x01,
    /// `bool`.
    Boolean = 0x02,
    /// `char`, a UTF-16 code unit.
    Char = 0x03,
    /// `sbyte`.
    I1 = 0x04,
    /// `byte`.
    U1 = 0x05,
    /// `short`.
    I2 = 0x06,
    /// `ushort`.
    U2 = 0x07,
    /// `int`.
    I4 = 0x08,
    /// `uint`.
    U4 = 0x09,
    /// `long`.
    I8 = 0x0A,
    /// `ulong`.
    U8 = 0x0B,
    /// `float`.
    R4 = 0x0C,
    /// `double`.
    R8 = 0x0D,
    /// `string`.
    String = 0x0E,
    /// An unmanaged pointer, `T*`; followed by `T`.
    Ptr = 0x0F,
    /// A managed reference, `ref T`; followed by `T`.
    ByRef = 0x10,
    /// A value type; followed by its `TypeDefOrRef` token.
    ValueType = 0x11,
    /// A reference type; followed by its `TypeDefOrRef` token.
    Class = 0x12,
    /// A generic parameter of the enclosing type (`!0`); followed by its index.
    Var = 0x13,
    /// A multi-dimensional or non-zero-based array, `T[,]`; followed by `T` and the shape.
    Array = 0x14,
    /// A generic instance, `G<A, B>`; followed by `G` and the arguments.
    GenericInst = 0x15,
    /// `System.TypedReference`.
    TypedByRef = 0x16,
    /// `nint` (`System.IntPtr`).
    I = 0x18,
    /// `nuint` (`System.UIntPtr`).
    U = 0x19,
    /// A function pointer, `delegate*<...>`; followed by a method signature.
    FnPtr = 0x1B,
    /// `object`.
    Object = 0x1C,
    /// A single-dimension, zero-based array, `T[]`; followed by `T`.
    SzArray = 0x1D,
    /// A generic parameter of the enclosing method (`!!0`); followed by its index.
    MVar = 0x1E,
    /// A required custom modifier, `modreq(M)`; followed by `M` and the modified type.
    CModReqd = 0x1F,
    /// An optional custom modifier, `modopt(M)`; followed by `M` and the modified type.
    CModOpt = 0x20,
    /// Runtime-internal type; never in a file.
    Internal = 0x21,
    /// Marks where the variable arguments start in a vararg call site.
    Sentinel = 0x41,
    /// Marks a local as `pinned` (`fixed` in C#); followed by its type.
    Pinned = 0x45,
}

/// The built-in types that signatures encode with their own element type
/// rather than a type token. `IntoStaticStr`/[`keyword`](Self::keyword) yields the C#
/// keyword (`to_string`); the BCL simple name (`Int32`, `IntPtr`, …) is an extra
/// parse alias so [`from_clr_name`](Self::from_clr_name) maps `System.*` names.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, FromRepr, IntoStaticStr, EnumString)]
#[repr(u8)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub enum PrimitiveType {
    /// `void`, `System.Void`.
    #[strum(to_string = "void", serialize = "Void")]
    Void = 0x01,
    /// `bool`, `System.Boolean`.
    #[strum(to_string = "bool", serialize = "Boolean")]
    Boolean = 0x02,
    /// `char`, `System.Char`.
    #[strum(to_string = "char", serialize = "Char")]
    Char = 0x03,
    /// `sbyte`, `System.SByte`.
    #[strum(to_string = "sbyte", serialize = "SByte")]
    I1 = 0x04,
    /// `byte`, `System.Byte`.
    #[strum(to_string = "byte", serialize = "Byte")]
    U1 = 0x05,
    /// `short`, `System.Int16`.
    #[strum(to_string = "short", serialize = "Int16")]
    I2 = 0x06,
    /// `ushort`, `System.UInt16`.
    #[strum(to_string = "ushort", serialize = "UInt16")]
    U2 = 0x07,
    /// `int`, `System.Int32`.
    #[strum(to_string = "int", serialize = "Int32")]
    I4 = 0x08,
    /// `uint`, `System.UInt32`.
    #[strum(to_string = "uint", serialize = "UInt32")]
    U4 = 0x09,
    /// `long`, `System.Int64`.
    #[strum(to_string = "long", serialize = "Int64")]
    I8 = 0x0A,
    /// `ulong`, `System.UInt64`.
    #[strum(to_string = "ulong", serialize = "UInt64")]
    U8 = 0x0B,
    /// `float`, `System.Single`.
    #[strum(to_string = "float", serialize = "Single")]
    R4 = 0x0C,
    /// `double`, `System.Double`.
    #[strum(to_string = "double", serialize = "Double")]
    R8 = 0x0D,
    /// `string`, `System.String`.
    #[strum(to_string = "string", serialize = "String")]
    String = 0x0E,
    /// `System.TypedReference`, the type of `__makeref` results.
    #[strum(to_string = "TypedReference")]
    TypedByRef = 0x16,
    /// `nint`, `System.IntPtr`.
    #[strum(to_string = "nint", serialize = "IntPtr")]
    I = 0x18,
    /// `nuint`, `System.UIntPtr`.
    #[strum(to_string = "nuint", serialize = "UIntPtr")]
    U = 0x19,
    /// `object`, `System.Object`.
    #[strum(to_string = "object", serialize = "Object")]
    Object = 0x1C,
}

impl PrimitiveType {
    /// The C# keyword, e.g. `"int"` for [`I4`](Self::I4).
    pub fn keyword(self) -> &'static str {
        self.into()
    }

    /// Resolves a BCL simple type name (`Int32`, `IntPtr`, `Object`, …) to its
    /// primitive. The C# keyword (`int`) also parses.
    pub fn from_clr_name(name: &str) -> Option<Self> {
        name.parse().ok()
    }

    /// Size in bytes for fixed size value types.
    pub fn size(self) -> Option<usize> {
        match self {
            Self::Boolean | Self::I1 | Self::U1 => Some(1),
            Self::Char | Self::I2 | Self::U2 => Some(2),
            Self::I4 | Self::U4 | Self::R4 => Some(4),
            Self::I8 | Self::U8 | Self::R8 => Some(8),
            _ => None,
        }
    }
}

/// The dimensions of a [`TypeSig::Array`]: its rank and, optionally, the size
/// and lower bound of the leading dimensions.
///
/// `int[,]` is rank 2 with no sizes or bounds. Sizes and bounds may cover fewer
/// dimensions than the rank; the rest are unspecified.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct ArrayShape {
    /// Number of dimensions.
    pub rank: u32,
    /// Sizes of the first `sizes.len()` dimensions.
    pub sizes: Vec<u32>,
    /// Lower bounds of the first `lo_bounds.len()` dimensions (C# arrays use 0).
    pub lo_bounds: Vec<i32>,
}

/// A type as it appears in a signature: a parameter, return, field, local or
/// generic argument type.
///
/// Named types are [`TypeDefOrRef`] handles into a module, so a `TypeSig` built
/// for one module should not be used in another without importing it.
///
/// ```
/// use hao::dotnet::signature::{PrimitiveType, TypeSig};
///
/// // int[]
/// let ints = TypeSig::sz_array(TypeSig::INT32);
/// // byte*
/// let bytes = TypeSig::ptr(TypeSig::Primitive(PrimitiveType::U1));
/// // ref int
/// let by_ref = TypeSig::ByRef(Box::new(TypeSig::INT32));
///
/// assert_eq!(ints, TypeSig::SzArray(Box::new(TypeSig::INT32)));
/// assert!(!bytes.is_void() && by_ref.type_def_or_ref().is_none());
/// ```
///
/// Class and value types need a type from the module, e.g. from
/// [`Module::corlib_type`](crate::Module::corlib_type) or
/// [`Module::import_type_from`](crate::Module::import_type_from), then
/// [`TypeSig::class`] or [`TypeSig::generic_class`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
#[cfg_attr(feature = "reflect", repr(C))]
pub enum TypeSig {
    /// A built-in type: `int`, `string`, `object`, ...
    Primitive(PrimitiveType),
    /// A struct or enum (`valuetype` in ILAsm).
    ValueType(TypeDefOrRef),
    /// A class, interface or delegate (`class` in ILAsm).
    Class(TypeDefOrRef),
    /// An unmanaged pointer, `T*`.
    Ptr(Box<TypeSig>),
    /// A managed reference, `ref T` / `out T` / `in T`.
    ByRef(Box<TypeSig>),
    /// A pinned local (`fixed` in C#), which the GC will not move. Only valid on
    /// locals.
    Pinned(Box<TypeSig>),
    /// A single-dimension, zero-based array, `T[]`.
    SzArray(Box<TypeSig>),
    /// Any other array, e.g. `T[,]`: see [`ArrayShape`].
    Array {
        /// The element type.
        element: Box<TypeSig>,
        /// The rank, sizes and lower bounds.
        shape: ArrayShape,
    },
    /// A generic type with arguments, e.g. `List<int>`.
    GenericInst {
        /// The open generic type, a [`Class`](Self::Class) or
        /// [`ValueType`](Self::ValueType) of e.g. ``List`1``.
        generic: Box<TypeSig>,
        /// The type arguments, one per generic parameter.
        args: Vec<TypeSig>,
    },
    /// Generic parameter of the enclosing type.
    Var(u32),
    /// Generic parameter of the enclosing method.
    MVar(u32),
    /// A function pointer, `delegate*<...>`, with its signature.
    FnPtr(Box<MethodSig>),
    /// A type with a custom modifier, `modreq(M) T` or `modopt(M) T`. C# emits
    /// these for e.g. `in` parameters, `volatile` fields and `init` setters.
    Modified {
        /// `true` for `modreq` (callers must understand it), `false` for `modopt`.
        required: bool,
        /// The modifier type, e.g. `System.Runtime.CompilerServices.IsVolatile`.
        modifier: TypeDefOrRef,
        /// The modified type.
        ty: Box<TypeSig>,
    },
}

impl Default for TypeSig {
    fn default() -> Self {
        Self::Primitive(PrimitiveType::Void)
    }
}

impl TypeSig {
    /// `void`.
    pub const VOID: Self = Self::Primitive(PrimitiveType::Void);
    /// `bool`.
    pub const BOOL: Self = Self::Primitive(PrimitiveType::Boolean);
    /// `char`.
    pub const CHAR: Self = Self::Primitive(PrimitiveType::Char);
    /// `int`.
    pub const INT32: Self = Self::Primitive(PrimitiveType::I4);
    /// `long`.
    pub const INT64: Self = Self::Primitive(PrimitiveType::I8);
    /// `double`.
    pub const FLOAT64: Self = Self::Primitive(PrimitiveType::R8);
    /// `string`.
    pub const STRING: Self = Self::Primitive(PrimitiveType::String);
    /// `object`.
    pub const OBJECT: Self = Self::Primitive(PrimitiveType::Object);
    /// `nint` / `System.IntPtr`.
    pub const NATIVE_INT: Self = Self::Primitive(PrimitiveType::I);

    /// A reference type: a class, interface or delegate.
    pub fn class(ty: TypeDefOrRef) -> Self {
        Self::Class(ty)
    }

    /// A value type: a struct or enum.
    pub fn value_type(ty: TypeDefOrRef) -> Self {
        Self::ValueType(ty)
    }

    /// `ty<args...>` for a generic class, e.g. `IEnumerable<int>`.
    pub fn generic_class(ty: TypeDefOrRef, args: Vec<TypeSig>) -> Self {
        Self::GenericInst {
            generic: Box::new(Self::Class(ty)),
            args,
        }
    }

    /// An unmanaged pointer, `element*`.
    pub fn ptr(element: TypeSig) -> Self {
        Self::Ptr(Box::new(element))
    }

    /// A single-dimension, zero-based array, `element[]`.
    pub fn sz_array(element: TypeSig) -> Self {
        Self::SzArray(Box::new(element))
    }

    /// Whether this is `void`, e.g. a method that returns nothing.
    pub fn is_void(&self) -> bool {
        matches!(self, Self::Primitive(PrimitiveType::Void))
    }

    /// The type with any custom modifiers and `pinned` removed.
    pub fn unmodified(&self) -> &TypeSig {
        match self {
            Self::Modified { ty, .. } | Self::Pinned(ty) => ty.unmodified(),
            t => t,
        }
    }

    /// The [`TypeDefOrRef`] for class / valuetype signatures.
    pub fn type_def_or_ref(&self) -> Option<&TypeDefOrRef> {
        match self.unmodified() {
            Self::ValueType(t) | Self::Class(t) => Some(t),
            Self::GenericInst { generic, .. } => generic.type_def_or_ref(),
            _ => None,
        }
    }
}

/// The kind of a signature blob, from the low 4 bits of its first byte
/// (ECMA-335 II.23.2.1-3). For method signatures this is the calling
/// convention; the other values mark field, local, property and generic
/// instance signatures.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, FromRepr)]
#[repr(u8)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub enum CallingConvention {
    #[default]
    /// A managed method: the normal convention.
    Default = 0x0,
    /// Native `cdecl`: the caller cleans the stack. Used by `calli` and P/Invoke.
    C = 0x1,
    /// Native `stdcall`: the callee cleans the stack (the Win32 API convention).
    StdCall = 0x2,
    /// Native C++ `thiscall`: `this` is passed in a register.
    ThisCall = 0x3,
    /// Native `fastcall`: the first arguments are passed in registers.
    FastCall = 0x4,
    /// A managed method with variable arguments (`__arglist`).
    VarArg = 0x5,
    /// A field signature.
    Field = 0x6,
    /// A method body's local variable signature.
    LocalSig = 0x7,
    /// A property signature.
    Property = 0x8,
    /// A native call whose convention is given by `CallConv*` modifiers on the
    /// return type (C# `delegate* unmanaged[...]`).
    Unmanaged = 0x9,
    /// A generic method instantiation (`MethodSpec`) signature.
    GenericInst = 0xA,
    /// A native vararg call. Rarely used.
    NativeVarArg = 0xB,
}

bitflags! {
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
    #[cfg_attr(feature = "reflect", derive(facet::Facet), facet(opaque))]
    /// The high bits of a signature's first byte.
    pub struct SignatureFlags: u8 {
        /// The method has generic parameters; see
        /// [`MethodSig::generic_param_count`].
        const GENERIC = 0x10;
        /// An instance method or property: it takes a hidden `this`.
        const HAS_THIS = 0x20;
        /// `this` is listed as the first parameter rather than implied. Used with
        /// `HAS_THIS`, mostly by function pointers.
        const EXPLICIT_THIS = 0x40;
    }
}

/// A method's signature: return type, parameter types, and calling convention.
///
/// It identifies a method alongside its name, so a reference to another
/// assembly's method must use the exact signature it was declared with.
///
/// ```
/// use hao::dotnet::signature::{MethodSig, TypeSig};
///
/// // static int Add(int, int)
/// let add = MethodSig::new_static(TypeSig::INT32, vec![TypeSig::INT32, TypeSig::INT32]);
/// assert!(!add.has_this());
///
/// // instance string ToString()
/// let to_string = MethodSig::new_instance(TypeSig::STRING, vec![]);
/// assert!(to_string.has_this());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct MethodSig {
    /// How it is called: [`Default`](CallingConvention::Default) for managed
    /// methods.
    pub calling_convention: CallingConvention,
    /// Whether it is an instance method and/or generic.
    pub flags: SignatureFlags,
    /// Number of generic parameters, used with [`SignatureFlags::GENERIC`].
    pub generic_param_count: u32,
    /// The return type; [`TypeSig::VOID`] for none.
    pub ret: TypeSig,
    /// Parameter types, not counting `this`.
    pub params: Vec<TypeSig>,
    /// Parameters after the vararg sentinel (call site signatures only).
    pub varargs: Vec<TypeSig>,
}

impl MethodSig {
    /// Whether this is an instance method, taking `this` as argument 0.
    pub fn has_this(&self) -> bool {
        self.flags.contains(SignatureFlags::HAS_THIS)
    }

    /// A static managed method.
    pub fn new_static(ret: TypeSig, params: Vec<TypeSig>) -> Self {
        Self {
            ret,
            params,
            ..Default::default()
        }
    }

    /// The signature of a native function with the C calling convention, for `calli`.
    pub fn native(ret: TypeSig, params: Vec<TypeSig>) -> Self {
        Self {
            calling_convention: CallingConvention::C,
            ret,
            params,
            ..Default::default()
        }
    }

    /// A `calli` signature with `CallingConvention::Unmanaged` and
    /// `modopt(CallConvSuppressGCTransition)` + `modopt(CallConvCdecl)`
    /// wrapping the return type, keeping the calling thread in cooperative
    /// GC mode for the duration of the call — the GC cannot relocate
    /// managed objects while such calls (or sequences of them, see
    /// [`callchain!`](crate::callchain)) are in flight.
    ///
    /// The modifier nesting order (suppress outermost) is what the runtime
    /// expects; pass the two `System.Runtime.CompilerServices` modifier
    /// types resolved via `Module::corlib_type`.
    pub fn unmanaged_suppress_gc(
        ret: TypeSig,
        params: Vec<TypeSig>,
        callconv_cdecl: &TypeDefOrRef,
        callconv_suppress: &TypeDefOrRef,
    ) -> Self {
        let wrapped_ret = TypeSig::Modified {
            required: false,
            modifier: callconv_suppress.clone(),
            ty: Box::new(TypeSig::Modified {
                required: false,
                modifier: callconv_cdecl.clone(),
                ty: Box::new(ret),
            }),
        };
        Self {
            calling_convention: CallingConvention::Unmanaged,
            ret: wrapped_ret,
            params,
            ..Default::default()
        }
    }

    /// An instance managed method (or constructor, with a `void` return).
    pub fn new_instance(ret: TypeSig, params: Vec<TypeSig>) -> Self {
        Self {
            flags: SignatureFlags::HAS_THIS,
            ret,
            params,
            ..Default::default()
        }
    }
}

/// A field's signature: just its type.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct FieldSig {
    /// The field's type.
    pub ty: TypeSig,
}

/// A property's signature: its type and, for indexers, parameter types.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct PropertySig {
    /// Whether it is an instance property.
    pub has_this: bool,
    /// The property's type.
    pub ty: TypeSig,
    /// Indexer parameter types (`this[int i]`); empty for ordinary properties.
    pub params: Vec<TypeSig>,
}

/// Signature of a [`MemberRef`](crate::dotnet::entries::MemberRef).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
#[cfg_attr(feature = "reflect", repr(C))]
pub enum MemberRefSig {
    /// A reference to a method.
    Method(MethodSig),
    /// A reference to a field.
    Field(FieldSig),
}

impl Default for MemberRefSig {
    fn default() -> Self {
        Self::Field(FieldSig::default())
    }
}

#[cfg(test)]
mod tests {
    use std::{cell::RefCell, collections::HashMap};

    use super::*;
    use crate::{
        dotnet::entries::{Entry, TypeRef},
        error::Result,
    };

    #[test]
    fn primitive_type_names() {
        // keyword() stays the C# keyword even though a BCL alias was added.
        assert_eq!(PrimitiveType::I4.keyword(), "int");
        assert_eq!(PrimitiveType::Object.keyword(), "object");
        assert_eq!(PrimitiveType::I.keyword(), "nint");
        // from_clr_name resolves the BCL simple name...
        assert_eq!(
            PrimitiveType::from_clr_name("Int32"),
            Some(PrimitiveType::I4)
        );
        assert_eq!(
            PrimitiveType::from_clr_name("IntPtr"),
            Some(PrimitiveType::I)
        );
        assert_eq!(
            PrimitiveType::from_clr_name("Object"),
            Some(PrimitiveType::Object)
        );
        assert_eq!(
            PrimitiveType::from_clr_name("TypedReference"),
            Some(PrimitiveType::TypedByRef)
        );
        // ...and the keyword also parses, but unknown names do not.
        assert_eq!(PrimitiveType::from_clr_name("int"), Some(PrimitiveType::I4));
        assert_eq!(PrimitiveType::from_clr_name("Nope"), None);
    }

    #[derive(Default)]
    struct Tokens(RefCell<HashMap<u32, Entry<TypeRef>>>);

    impl TokenResolver for Tokens {
        fn type_def_or_ref(&self, coded: u32) -> Result<TypeDefOrRef> {
            let entry = self
                .0
                .borrow_mut()
                .entry(coded)
                .or_insert_with(|| {
                    Entry::new(TypeRef {
                        name: format!("T{}", coded),
                        ..Default::default()
                    })
                })
                .clone();
            Ok(TypeDefOrRef::TypeRef(entry))
        }
    }

    impl TokenEncoder for Tokens {
        fn type_def_or_ref(&mut self, ty: &TypeDefOrRef) -> Result<u32> {
            let TypeDefOrRef::TypeRef(t) = ty else {
                unreachable!()
            };
            Ok(*self.0.borrow().iter().find(|(_, e)| e.ptr_eq(t)).unwrap().0)
        }
    }

    fn method(blob: &[u8]) -> MethodSig {
        SignatureReader::new(blob, &Tokens::default())
            .read_method_sig()
            .unwrap()
    }

    fn write_method(sig: &MethodSig, tokens: &mut Tokens) -> Vec<u8> {
        let mut w = SignatureWriter::new(tokens);
        w.write_method_sig(sig).unwrap();
        w.finish()
    }

    #[test]
    fn instance_method() {
        let sig = method(&[0x20, 0x02, 0x08, 0x08, 0x0E]);
        assert!(sig.has_this());
        assert_eq!(sig.ret, TypeSig::Primitive(PrimitiveType::I4));
        assert_eq!(
            sig.params,
            [
                TypeSig::Primitive(PrimitiveType::I4),
                TypeSig::Primitive(PrimitiveType::String)
            ]
        );
    }

    #[test]
    fn signed_and_unsigned_bytes_are_not_swapped() {
        let tokens = Tokens::default();
        let field = SignatureReader::new(&[0x06, 0x04], &tokens)
            .read_field_sig()
            .unwrap();
        assert_eq!(field.ty, TypeSig::Primitive(PrimitiveType::I1));
        assert_eq!(PrimitiveType::I1.keyword(), "sbyte");
        let field = SignatureReader::new(&[0x06, 0x19], &tokens)
            .read_field_sig()
            .unwrap();
        assert_eq!(field.ty, TypeSig::Primitive(PrimitiveType::U));
    }

    #[test]
    fn varargs_after_sentinel() {
        let sig = method(&[0x05, 0x03, 0x01, 0x08, 0x41, 0x0A, 0x0D]);
        assert_eq!(sig.calling_convention, CallingConvention::VarArg);
        assert_eq!(sig.params, [TypeSig::Primitive(PrimitiveType::I4)]);
        assert_eq!(
            sig.varargs,
            [
                TypeSig::Primitive(PrimitiveType::I8),
                TypeSig::Primitive(PrimitiveType::R8)
            ]
        );
    }

    #[test]
    fn array_shape_with_negative_bounds() {
        let blob = [0x06, 0x14, 0x08, 0x02, 0x02, 0x03, 0x04, 0x02, 0x00, 0x7B];
        let tokens = Tokens::default();
        let field = SignatureReader::new(&blob, &tokens)
            .read_field_sig()
            .unwrap();
        let TypeSig::Array { shape, .. } = field.ty else {
            panic!()
        };
        assert_eq!(
            shape,
            ArrayShape {
                rank: 2,
                sizes: vec![3, 4],
                lo_bounds: vec![0, -3]
            }
        );
    }

    #[test]
    fn compressed_signed_integers() {
        let mut tokens = Tokens::default();
        for (value, encoded) in [
            (3, &[0x06][..]),
            (-3, &[0x7B]),
            (64, &[0x80, 0x80]),
            (-64, &[0x01]),
            (8192, &[0xC0, 0x00, 0x40, 0x00]),
            (-8192, &[0x80, 0x01]),
            (268435455, &[0xDF, 0xFF, 0xFF, 0xFE]),
            (-268435456, &[0xC0, 0x00, 0x00, 0x01]),
        ] {
            let mut w = SignatureWriter::new(&mut tokens);
            w.write_compressed_i32(value).unwrap();
            assert_eq!(w.finish(), encoded, "encoding {}", value);
            let decoded = SignatureReader::new(encoded, &Tokens::default())
                .read_compressed_i32()
                .unwrap();
            assert_eq!(decoded, value);
        }
    }

    #[test]
    fn generic_method_with_modifiers_round_trips() {
        // generic<1> instance void (class T5, valuetype T6<!!0>[], modreq(T9) int32&, int32[0...,-3...])
        let blob = [
            0x30, 0x01, 0x04, 0x01, 0x12, 0x05, 0x1D, 0x15, 0x11, 0x06, 0x01, 0x1E, 0x00, 0x1F,
            0x09, 0x10, 0x08, 0x14, 0x08, 0x02, 0x00, 0x02, 0x00, 0x7B,
        ];
        let mut tokens = Tokens::default();
        let sig = SignatureReader::new(&blob, &tokens)
            .read_method_sig()
            .unwrap();
        assert_eq!(sig.generic_param_count, 1);
        assert_eq!(sig.params.len(), 4);
        assert!(matches!(
            &sig.params[2],
            TypeSig::Modified { required: true, .. }
        ));
        assert_eq!(write_method(&sig, &mut tokens), blob);
    }
}