-
-
Notifications
You must be signed in to change notification settings - Fork 52
/
Meta.cs
1218 lines (1083 loc) · 49.9 KB
/
Meta.cs
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
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Xml;
using Towel.DataStructures;
using static Towel.Statics;
namespace Towel
{
/// <summary>Constains static analysis methods of the code (reflection).</summary>
public static class Meta
{
#region Getting Methods Via Reflection
#region System.Type.GetMethod
#if false
/// <summary>Gets a method on a type by signature.</summary>
/// <typeparam name="Signature">
/// The signature of the method to get as a delegate type. Must match the
/// method in return type, parameter types, generic types, parameter names,
/// generic parameter names, and delegate/method name.
/// </typeparam>
/// <param name="declaringType">The declaring type of the method to get.</param>
/// <returns>The method info if found. null if not.</returns>
public static MethodInfo GetMethod<Signature>(this Type declaringType)
where Signature : Delegate
{
Type signature = typeof(Signature);
string name = Regex.Replace(signature.Name, @"`\d+", string.Empty);
Type[] signatureGenerics = signature.GetGenericArguments();
MethodInfo signatureMethodInfo = signature.GetMethod("Invoke");
ParameterInfo[] signatureParameters = signatureMethodInfo.GetParameters();
Type signatureGeneric = signature.GetGenericTypeDefinition();
Type[] signatureGenericGenerics = signatureGeneric.GetGenericArguments();
foreach (MethodInfo currentMethodInfo in declaringType.GetMethods(
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic))
{
MethodInfo methodInfo = currentMethodInfo;
if (methodInfo.Name != name ||
signature.IsGenericType != methodInfo.IsGenericMethod)
{
continue;
}
if (signature.IsGenericType)
{
Type[] methodInfoGenerics = methodInfo.GetGenericArguments();
if (methodInfoGenerics.Length != signatureGenerics.Length ||
!Equate<Type>(signatureGenericGenerics, methodInfoGenerics, (a, b) => a.Name == b.Name))
{
continue;
}
try
{
methodInfo = methodInfo.MakeGenericMethod(signatureGenerics);
}
catch (ArgumentException)
{
// this is likely a contraint validation error
continue;
}
}
if (signatureMethodInfo.ReturnType != methodInfo.ReturnType ||
!Equate<ParameterInfo>(signatureParameters, methodInfo.GetParameters(), (a, b) => a.ParameterType == b.ParameterType && a.Name == b.Name))
{
continue;
}
return methodInfo;
}
return null;
}
#endif
#endregion
#region GetTryParseMethod
/// <summary>Gets the TryParse <see cref="MethodInfo"/> on a type if it exists [<see cref="bool"/> TryParse(<see cref="string"/>, out <typeparamref name="T"/>)].</summary>
/// <typeparam name="T">The type of the out parameter.</typeparam>
/// <returns>The TryParse <see cref="MethodInfo"/> if found or null if not.</returns>
public static MethodInfo? GetTryParseMethod<T>() => GetTryParseMethodCache<T>.Value;
/// <summary>Gets the TryParse <see cref="MethodInfo"/> on a type if it exists [<see cref="bool"/> TryParse(<see cref="string"/>, out <paramref name="a"/>)].</summary>
/// <param name="a">The type of the out parameter.</param>
/// <returns>The TryParse <see cref="MethodInfo"/> if found or null if not.</returns>
public static MethodInfo? GetTryParseMethod(Type a)
{
_ = a ?? throw new ArgumentNullException(nameof(a));
MethodInfo? methodInfo = a.GetMethod("TryParse",
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic,
null,
Ɐ(typeof(string), a.MakeByRefType()),
null);
return methodInfo is not null && methodInfo.ReturnType == typeof(bool)
? methodInfo
: null;
}
internal static class GetTryParseMethodCache<T>
{
internal static readonly MethodInfo? Value = GetTryParseMethod(typeof(T));
}
#endregion
#region GetFactorialMethod
/// <summary>Gets the Factorial <see cref="MethodInfo"/> on a type if it exists [<see cref="bool"/> Factorial(<typeparamref name="T"/>)].</summary>
/// <typeparam name="T">The type of the out parameter.</typeparam>
/// <returns>The IsPrime <see cref="MethodInfo"/> if found or null if not.</returns>
public static MethodInfo? GetFactorialMethod<T>() => GetFactorialMethodCache<T>.Value;
/// <summary>Gets the Factorial <see cref="MethodInfo"/> on a type if it exists [<see cref="bool"/> Factorial(<paramref name="a"/>)].</summary>
/// <param name="a">The type of the out parameter.</param>
/// <returns>The IsNonNegative <see cref="MethodInfo"/> if found or null if not.</returns>
public static MethodInfo? GetFactorialMethod(Type a)
{
_ = a ?? throw new ArgumentNullException(nameof(a));
MethodInfo? methodInfo = a.GetMethod("Factorial",
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic,
null,
Ɐ(a),
null);
return methodInfo is not null && methodInfo.ReturnType == typeof(bool)
? methodInfo
: null;
}
internal static class GetFactorialMethodCache<T>
{
internal static readonly MethodInfo? Value = GetFactorialMethod(typeof(T));
}
#endregion
#region GetIsPrimeMethod
/// <summary>Gets the IsPrime <see cref="MethodInfo"/> on a type if it exists [<see cref="bool"/> IsPrime(<typeparamref name="T"/>)].</summary>
/// <typeparam name="T">The type of the out parameter.</typeparam>
/// <returns>The IsPrime <see cref="MethodInfo"/> if found or null if not.</returns>
public static MethodInfo? GetIsPrimeMethod<T>() => GetIsPrimeMethodCache<T>.Value;
/// <summary>Gets the IsPrime <see cref="MethodInfo"/> on a type if it exists [<see cref="bool"/> IsPrime(<paramref name="a"/>)].</summary>
/// <param name="a">The type of the out parameter.</param>
/// <returns>The IsNonNegative <see cref="MethodInfo"/> if found or null if not.</returns>
public static MethodInfo? GetIsPrimeMethod(Type a)
{
_ = a ?? throw new ArgumentNullException(nameof(a));
MethodInfo? methodInfo = a.GetMethod("IsPrime",
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic,
null,
Ɐ(a),
null);
return methodInfo is not null && methodInfo.ReturnType == typeof(bool)
? methodInfo
: null;
}
internal static class GetIsPrimeMethodCache<T>
{
internal static readonly MethodInfo? Value = GetIsPrimeMethod(typeof(T));
}
#endregion
#region GetIsNonNegativeMethod
/// <summary>Gets the IsNonNegative <see cref="MethodInfo"/> on a type if it exists [<see cref="bool"/> IsNonNegative(<typeparamref name="T"/>)].</summary>
/// <typeparam name="T">The type of the out parameter.</typeparam>
/// <returns>The IsNonNegative <see cref="MethodInfo"/> if found or null if not.</returns>
public static MethodInfo? GetIsNonNegativeMethod<T>() => GetIsNonNegativeMethodCache<T>.Value;
/// <summary>Gets the IsNonNegative <see cref="MethodInfo"/> on a type if it exists [<see cref="bool"/> IsNonNegative(<paramref name="a"/>)].</summary>
/// <param name="a">The type of the out parameter.</param>
/// <returns>The IsNonNegative <see cref="MethodInfo"/> if found or null if not.</returns>
public static MethodInfo? GetIsNonNegativeMethod(Type a)
{
_ = a ?? throw new ArgumentNullException(nameof(a));
MethodInfo? methodInfo = a.GetMethod("IsNonNegative",
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic,
null,
Ɐ(a),
null);
return methodInfo is not null && methodInfo.ReturnType == typeof(bool)
? methodInfo
: null;
}
internal static class GetIsNonNegativeMethodCache<T>
{
internal static readonly MethodInfo? Value = GetIsNonNegativeMethod(typeof(T));
}
#endregion
#region GetIsNegativeMethod
/// <summary>Gets the IsNegative <see cref="MethodInfo"/> on a type if it exists [<see cref="bool"/> IsNegative(<typeparamref name="T"/>)].</summary>
/// <typeparam name="T">The type of the out parameter.</typeparam>
/// <returns>The IsNegative <see cref="MethodInfo"/> if found or null if not.</returns>
public static MethodInfo? GetIsNegativeMethod<T>() => GetIsNegativeMethodCache<T>.Value;
/// <summary>Gets the IsNegative <see cref="MethodInfo"/> on a type if it exists [<see cref="bool"/> IsNegative(<paramref name="a"/>)].</summary>
/// <param name="a">The type of the out parameter.</param>
/// <returns>The IsNegative <see cref="MethodInfo"/> if found or null if not.</returns>
public static MethodInfo? GetIsNegativeMethod(Type a)
{
_ = a ?? throw new ArgumentNullException(nameof(a));
MethodInfo? methodInfo = a.GetMethod("IsNegative",
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic,
null,
Ɐ(a),
null);
return methodInfo is not null && methodInfo.ReturnType == typeof(bool)
? methodInfo
: null;
}
internal static class GetIsNegativeMethodCache<T>
{
internal static readonly MethodInfo? Value = GetIsNegativeMethod(typeof(T));
}
#endregion
#region GetIsPositiveMethod
/// <summary>Gets the IsPositive <see cref="MethodInfo"/> on a type if it exists [<see cref="bool"/> IsPositive(<typeparamref name="T"/>)].</summary>
/// <typeparam name="T">The type of the out parameter.</typeparam>
/// <returns>The IsPositive <see cref="MethodInfo"/> if found or null if not.</returns>
public static MethodInfo? GetIsPositiveMethod<T>() => GetIsPositiveMethodCache<T>.Value;
/// <summary>Gets the IsPositive <see cref="MethodInfo"/> on a type if it exists [<see cref="bool"/> IsPositive(<paramref name="a"/>)].</summary>
/// <param name="a">The type of the out parameter.</param>
/// <returns>The IsPositive <see cref="MethodInfo"/> if found or null if not.</returns>
public static MethodInfo? GetIsPositiveMethod(Type a)
{
_ = a ?? throw new ArgumentNullException(nameof(a));
MethodInfo? methodInfo = a.GetMethod("IsPositive",
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic,
null,
Ɐ(a),
null);
return methodInfo is not null && methodInfo.ReturnType == typeof(bool)
? methodInfo
: null;
}
internal static class GetIsPositiveMethodCache<T>
{
internal static readonly MethodInfo? Value = GetIsPositiveMethod(typeof(T));
}
#endregion
#region GetIsEvenMethod
/// <summary>Gets the IsEven <see cref="MethodInfo"/> on a type if it exists [<see cref="bool"/> IsEven(<typeparamref name="T"/>)].</summary>
/// <typeparam name="T">The type of the out parameter.</typeparam>
/// <returns>The IsEven <see cref="MethodInfo"/> if found or null if not.</returns>
public static MethodInfo? GetIsEvenMethod<T>() => GetIsEvenMethodCache<T>.Value;
/// <summary>Gets the IsEven <see cref="MethodInfo"/> on a type if it exists [<see cref="bool"/> IsEven(<paramref name="a"/>)].</summary>
/// <param name="a">The type of the out parameter.</param>
/// <returns>The IsEven <see cref="MethodInfo"/> if found or null if not.</returns>
public static MethodInfo? GetIsEvenMethod(Type a)
{
_ = a ?? throw new ArgumentNullException(nameof(a));
MethodInfo? methodInfo = a.GetMethod(
"IsOdd",
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic,
null,
Ɐ(a),
null);
return methodInfo is not null && methodInfo.ReturnType == typeof(bool)
? methodInfo
: null;
}
internal static class GetIsEvenMethodCache<T>
{
internal static readonly MethodInfo? Value = GetIsEvenMethod(typeof(T));
}
#endregion
#region GetIsOddMethod
/// <summary>Gets the IsOdd <see cref="MethodInfo"/> on a type if it exists [<see cref="bool"/> IsOdd(<typeparamref name="T"/>)].</summary>
/// <typeparam name="T">The type of the out parameter.</typeparam>
/// <returns>The IsOdd <see cref="MethodInfo"/> if found or null if not.</returns>
public static MethodInfo? GetIsOddMethod<T>() => GetIsOddMethodCache<T>.Value;
/// <summary>Gets the IsOdd <see cref="MethodInfo"/> on a type if it exists [<see cref="bool"/> IsOdd(<paramref name="a"/>)].</summary>
/// <param name="a">The type of the out parameter.</param>
/// <returns>The IsOdd <see cref="MethodInfo"/> if found or null if not.</returns>
public static MethodInfo? GetIsOddMethod(Type a)
{
_ = a ?? throw new ArgumentNullException(nameof(a));
MethodInfo? methodInfo = a.GetMethod(
"IsOdd",
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic,
null,
Ɐ(a),
null);
return methodInfo is not null && methodInfo.ReturnType == typeof(bool)
? methodInfo
: null;
}
internal static class GetIsOddMethodCache<T>
{
internal static readonly MethodInfo? Value = GetIsOddMethod(typeof(T));
}
#endregion
#region GetIsIntegerMethod
/// <summary>Gets the IsInteger <see cref="MethodInfo"/> on a type if it exists [<see cref="bool"/> IsInteger(<typeparamref name="T"/>)].</summary>
/// <typeparam name="T">The type of the out parameter.</typeparam>
/// <returns>The TryParse <see cref="MethodInfo"/> if found or null if not.</returns>
public static MethodInfo? GetIsIntegerMethod<T>() => GetIsIntegerMethodCache<T>.Value;
/// <summary>Gets the IsInteger <see cref="MethodInfo"/> on a type if it exists [<see cref="bool"/> IsInteger(<paramref name="a"/>)].</summary>
/// <param name="a">The type of the out parameter.</param>
/// <returns>The TryParse <see cref="MethodInfo"/> if found or null if not.</returns>
public static MethodInfo? GetIsIntegerMethod(Type a)
{
_ = a ?? throw new ArgumentNullException(nameof(a));
MethodInfo? methodInfo = a.GetMethod(
"IsInteger",
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic,
null,
Ɐ(a),
null);
return methodInfo is not null && methodInfo.ReturnType == typeof(bool)
? methodInfo
: null;
}
internal static class GetIsIntegerMethodCache<T>
{
internal static readonly MethodInfo? Value = GetIsIntegerMethod(typeof(T));
}
#endregion
#region GetLessThanMethod
/// <summary>Determines if an op_LessThan member exists.</summary>
/// <typeparam name="TA">The type of the left operand.</typeparam>
/// <typeparam name="TB">The type of the right operand.</typeparam>
/// <typeparam name="TC">The type of the return.</typeparam>
/// <returns>True if the op_LessThan member exists or false if not.</returns>
public static MethodInfo? GetLessThanMethod<TA, TB, TC>() => GetLessThanMethodCache<TA, TB, TC>.Value;
/// <summary>Determines if an op_LessThan member exists.</summary>
/// <param name="a">The type of the left operand.</param>
/// <param name="b">The type of the right operand.</param>
/// <param name="c">The type of the return.</param>
/// <returns>True if the op_LessThan member exists or false if not.</returns>
internal static MethodInfo? GetLessThanMethod(Type a, Type b, Type c)
{
_ = a ?? throw new ArgumentNullException(nameof(a));
_ = b ?? throw new ArgumentNullException(nameof(b));
MethodInfo? CheckType(Type type)
{
MethodInfo? methodInfo = type.GetMethod(
"op_LessThan",
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic,
null,
Ɐ(a, b),
null);
return methodInfo is not null
&& methodInfo.ReturnType == c
&& methodInfo.IsSpecialName
? methodInfo
: null;
}
return CheckType(a) ?? CheckType(b);
}
internal static class GetLessThanMethodCache<TA, TB, TC>
{
internal static readonly MethodInfo? Value = GetLessThanMethod(typeof(TA), typeof(TB), typeof(TC));
}
#endregion
#region GetGreaterThanMethod
/// <summary>Determines if an op_GreaterThan member exists.</summary>
/// <typeparam name="TA">The type of the left operand.</typeparam>
/// <typeparam name="TB">The type of the right operand.</typeparam>
/// <typeparam name="TC">The type of the return.</typeparam>
/// <returns>True if the op_GreaterThan member exists or false if not.</returns>
public static MethodInfo? GetGreaterThanMethod<TA, TB, TC>() => GetGreaterThanMethodCache<TA, TB, TC>.Value;
/// <summary>Determines if an op_GreaterThan member exists.</summary>
/// <param name="a">The type of the left operand.</param>
/// <param name="b">The type of the right operand.</param>
/// <param name="c">The type of the return.</param>
/// <returns>True if the op_GreaterThan member exists or false if not.</returns>
internal static MethodInfo? GetGreaterThanMethod(Type a, Type b, Type c)
{
_ = a ?? throw new ArgumentNullException(nameof(a));
_ = b ?? throw new ArgumentNullException(nameof(b));
MethodInfo? CheckType(Type type)
{
MethodInfo? methodInfo = type.GetMethod(
"op_GreaterThan",
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic,
null,
Ɐ(a, b),
null);
return methodInfo is not null
&& methodInfo.ReturnType == c
&& methodInfo.IsSpecialName
? methodInfo
: null;
}
return CheckType(a) ?? CheckType(b);
}
internal static class GetGreaterThanMethodCache<TA, TB, TC>
{
internal static readonly MethodInfo? Value = GetGreaterThanMethod(typeof(TA), typeof(TB), typeof(TC));
}
#endregion
#endregion
#region Has[Implicit|Explicit]Cast
/// <summary>Determines if an implicit casting operator exists from one type to another.</summary>
/// <typeparam name="TFrom">The parameter type of the implicit casting operator.</typeparam>
/// <typeparam name="TTo">The return type fo the implicit casting operator.</typeparam>
/// <returns>True if the implicit casting operator exists or false if not.</returns>
public static bool HasImplicitCast<TFrom, TTo>() => HasCastCache<TFrom, TTo>.Implicit;
/// <summary>Determines if an implicit casting operator exists from one type to another.</summary>
/// <typeparam name="TFrom">The parameter type of the implicit casting operator.</typeparam>
/// <typeparam name="TTo">The return type fo the implicit casting operator.</typeparam>
/// <returns>True if the implicit casting operator exists or false if not.</returns>
public static bool HasExplicitCast<TFrom, TTo>() => HasCastCache<TFrom, TTo>.Implicit;
/// <summary>Determines if an implicit casting operator exists from one type to another.</summary>
/// <param name="fromType">The parameter type of the implicit casting operator.</param>
/// <param name="toType">The return type fo the implicit casting operator.</param>
/// <returns>True if the implicit casting operator exists or false if not.</returns>
public static bool HasImplicitCast(Type fromType, Type toType) => HasCast(fromType, toType, true);
/// <summary>Determines if an implicit casting operator exists from one type to another.</summary>
/// <param name="fromType">The parameter type of the implicit casting operator.</param>
/// <param name="toType">The return type fo the implicit casting operator.</param>
/// <returns>True if the implicit casting operator exists or false if not.</returns>
public static bool HasExplicitCast(Type fromType, Type toType) => HasCast(fromType, toType, false);
internal static bool HasCast(Type fromType, Type toType, bool @implicit)
{
_ = fromType ?? throw new ArgumentNullException(nameof(fromType));
_ = toType ?? throw new ArgumentNullException(nameof(toType));
string methodName = @implicit
? "op_Implicit"
: "op_Explicit";
bool CheckType(Type type)
{
MethodInfo? methodInfo = type.GetMethod(
methodName,
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic,
null,
Ɐ(fromType),
null);
return methodInfo is not null
&& methodInfo.ReturnType == toType
&& methodInfo.IsSpecialName;
}
if (CheckType(fromType) || CheckType(toType))
{
return true;
}
return false;
}
internal static class HasCastCache<TFrom, TTo>
{
internal static readonly bool Implicit = HasCast(typeof(TFrom), typeof(TTo), true);
internal static readonly bool Explicit = HasCast(typeof(TFrom), typeof(TTo), false);
}
#endregion
#region System.Type.ConvertToCSharpSource
/// <summary>Converts a <see cref="System.Type"/> into a <see cref="string"/> as it would appear in C# source code.</summary>
/// <param name="type">The <see cref="System.Type"/> to convert to a <see cref="string"/>.</param>
/// <param name="showGenericParameters">If the generic parameters are the generic types, whether they should be shown or not.</param>
/// <returns>The <see cref="string"/> as the <see cref="System.Type"/> would appear in C# source code.</returns>
public static string ConvertToCSharpSource(this Type type, bool showGenericParameters = false)
{
IQueue<Type> genericParameters = new QueueArray<Type>();
type.GetGenericArguments().Stepper(x => genericParameters.Enqueue(x));
return ConvertToCsharpSource(type);
string ConvertToCsharpSource(Type type)
{
_ = type ?? throw new ArgumentNullException(nameof(type));
string result = type.IsNested
? ConvertToCsharpSource(type.DeclaringType ?? throw new ArgumentException($"{nameof(type)}.{nameof(Type.DeclaringType)} is null", nameof(type))) + "."
: type.Namespace + ".";
result += Regex.Replace(type.Name, "`.*", string.Empty);
if (type.IsGenericType)
{
result += "<";
bool firstIteration = true;
foreach (Type generic in type.GetGenericArguments())
{
if (genericParameters.Count <= 0)
{
break;
}
Type correctGeneric = genericParameters.Dequeue();
result += (firstIteration ? string.Empty : ",") +
(correctGeneric.IsGenericParameter
? (showGenericParameters ? (firstIteration ? string.Empty : " ") + correctGeneric.Name : string.Empty)
: (firstIteration ? string.Empty : " ") + ConvertToCSharpSource(correctGeneric, showGenericParameters));
firstIteration = false;
}
result += ">";
}
return result;
}
}
#endregion
#region System.Enum
/// <summary>Gets a custom attribute on an enum value by generic type.</summary>
/// <typeparam name="TAttribute">The type of attribute to get.</typeparam>
/// <param name="enum">The enum value to get the attribute of.</param>
/// <returns>The attribute on the enum value of the provided type.</returns>
public static TAttribute? GetEnumAttribute<TAttribute>(this Enum @enum)
where TAttribute : Attribute
{
Type type = @enum.GetType();
MemberInfo memberInfo = type.GetMember(@enum.ToString())[0];
return memberInfo.GetCustomAttribute<TAttribute>();
}
/// <summary>Gets custom attributes on an enum value by generic type.</summary>
/// <typeparam name="TAttribute">The type of attribute to get.</typeparam>
/// <param name="enum">The enum value to get the attribute of.</param>
/// <returns>The attributes on the enum value of the provided type.</returns>
public static System.Collections.Generic.IEnumerable<TAttribute> GetEnumAttributes<TAttribute>(this Enum @enum)
where TAttribute : Attribute
{
Type type = @enum.GetType();
MemberInfo memberInfo = type.GetMember(@enum.ToString())[0];
return memberInfo.GetCustomAttributes<TAttribute>();
}
/// <summary>Gets the maximum value of an enum.</summary>
/// <typeparam name="TEnum">The enum type to get the maximum value of.</typeparam>
/// <returns>The maximum enum value of the provided type.</returns>
public static TEnum GetLastEnumValue<TEnum>()
where TEnum : struct, Enum
{
TEnum[] values = (TEnum[])Enum.GetValues(typeof(TEnum));
if (values.Length is 0)
{
throw new InvalidOperationException("Attempting to get the last enum value of an enum type with no values.");
}
return values[^1];
}
#endregion
#region System.Reflection.Assembly
/// <summary>Enumerates through all the events with a custom attribute.</summary>
/// <typeparam name="TAttribute">The type of the custom attribute.</typeparam>
/// <param name="assembly">The assembly to iterate through the events of.</param>
/// <returns>The IEnumerable of the events with the provided attribute type.</returns>
public static System.Collections.Generic.IEnumerable<EventInfo> GetEventInfosWithAttribute<TAttribute>(this Assembly assembly)
where TAttribute : Attribute
{
foreach (Type type in assembly.GetTypes())
{
foreach (EventInfo eventInfo in type.GetEvents(
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic))
{
if (eventInfo.GetCustomAttributes(typeof(TAttribute), true).Length > 0)
{
yield return eventInfo;
}
}
}
}
/// <summary>Enumerates through all the constructors with a custom attribute.</summary>
/// <typeparam name="TAttribute">The type of the custom attribute.</typeparam>
/// <param name="assembly">The assembly to iterate through the constructors of.</param>
/// <returns>The IEnumerable of the constructors with the provided attribute type.</returns>
public static System.Collections.Generic.IEnumerable<ConstructorInfo> GetConstructorInfosWithAttribute<TAttribute>(this Assembly assembly)
where TAttribute : Attribute
{
foreach (Type type in assembly.GetTypes())
{
foreach (ConstructorInfo constructorInfo in type.GetConstructors(
BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.NonPublic))
{
if (constructorInfo.GetCustomAttributes(typeof(TAttribute), true).Length > 0)
{
yield return constructorInfo;
}
}
}
}
/// <summary>Enumerates through all the properties with a custom attribute.</summary>
/// <typeparam name="TAttribute">The type of the custom attribute.</typeparam>
/// <param name="assembly">The assembly to iterate through the properties of.</param>
/// <returns>The IEnumerable of the properties with the provided attribute type.</returns>
public static System.Collections.Generic.IEnumerable<PropertyInfo> GetPropertyInfosWithAttribute<TAttribute>(this Assembly assembly)
where TAttribute : Attribute
{
foreach (Type type in assembly.GetTypes())
{
foreach (PropertyInfo propertyInfo in type.GetProperties(
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic))
{
if (propertyInfo.GetCustomAttributes(typeof(TAttribute), true).Length > 0)
{
yield return propertyInfo;
}
}
}
}
/// <summary>Enumerates through all the fields with a custom attribute.</summary>
/// <typeparam name="TAttribute">The type of the custom attribute.</typeparam>
/// <param name="assembly">The assembly to iterate through the fields of.</param>
/// <returns>The IEnumerable of the fields with the provided attribute type.</returns>
public static System.Collections.Generic.IEnumerable<FieldInfo> GetFieldInfosWithAttribute<TAttribute>(this Assembly assembly)
where TAttribute : Attribute
{
foreach (Type type in assembly.GetTypes())
{
foreach (FieldInfo fieldInfo in type.GetFields(
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic))
{
if (fieldInfo.GetCustomAttributes(typeof(TAttribute), true).Length > 0)
{
yield return fieldInfo;
}
}
}
}
/// <summary>Enumerates through all the methods with a custom attribute.</summary>
/// <typeparam name="TAttribute">The type of the custom attribute.</typeparam>
/// <param name="assembly">The assembly to iterate through the methods of.</param>
/// <returns>The IEnumerable of the methods with the provided attribute type.</returns>
public static System.Collections.Generic.IEnumerable<MethodInfo> GetMethodInfosWithAttribute<TAttribute>(this Assembly assembly)
where TAttribute : Attribute
{
foreach (Type type in assembly.GetTypes())
{
foreach (MethodInfo methodInfo in type.GetMethods(
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic))
{
if (methodInfo.GetCustomAttributes(typeof(TAttribute), true).Length > 0)
{
yield return methodInfo;
}
}
}
}
/// <summary>Enumerates through all the types with a custom attribute.</summary>
/// <typeparam name="TAttribute">The type of the custom attribute.</typeparam>
/// <param name="assembly">The assembly to iterate through the types of.</param>
/// <returns>The IEnumerable of the types with the provided attribute type.</returns>
public static System.Collections.Generic.IEnumerable<Type> GetTypesWithAttribute<TAttribute>(this Assembly assembly)
where TAttribute : Attribute
{
foreach (Type type in assembly.GetTypes())
{
if (type.GetCustomAttributes(typeof(TAttribute), true).Length > 0)
{
yield return type;
}
}
}
/// <summary>Gets all the types in an assembly that derive from a base.</summary>
/// <typeparam name="TBase">The base type to get the deriving types of.</typeparam>
/// <param name="assembly">The assmebly to perform the search on.</param>
/// <returns>The IEnumerable of the types that derive from the provided base.</returns>
public static System.Collections.Generic.IEnumerable<Type> GetDerivedTypes<TBase>(this Assembly assembly)
{
Type @base = typeof(TBase);
return assembly.GetTypes().Where(type =>
type != @base &&
@base.IsAssignableFrom(type));
}
/// <summary>Gets the file path of an assembly.</summary>
/// <param name="assembly">The assembly to get the file path of.</param>
/// <returns>The file path of the assembly.</returns>
public static string? GetDirectoryPath(this Assembly assembly)
{
string? directoryPath = Path.GetDirectoryName(assembly.Location);
return directoryPath == string.Empty ? null : directoryPath;
}
#endregion
#region GetXmlName
/// <summary>Gets the XML name of an <see cref="Type"/> as it appears in the XML docs.</summary>
/// <param name="type">The field to get the XML name of.</param>
/// <returns>The XML name of <paramref name="type"/> as it appears in the XML docs.</returns>
public static string GetXmlName(this Type type)
{
_ = type ?? throw new ArgumentNullException(nameof(type));
_ = type.FullName ?? throw new ArgumentException($"{nameof(type)}.{nameof(Type.FullName)} is null", nameof(type));
LoadXmlDocumentation(type.Assembly);
return "T:" + GetXmlNameTypeSegment(type.FullName);
}
/// <summary>Gets the XML name of an <see cref="MethodInfo"/> as it appears in the XML docs.</summary>
/// <param name="methodInfo">The field to get the XML name of.</param>
/// <returns>The XML name of <paramref name="methodInfo"/> as it appears in the XML docs.</returns>
public static string GetXmlName(this MethodInfo methodInfo)
{
_ = methodInfo ?? throw new ArgumentNullException(nameof(methodInfo));
_ = methodInfo.DeclaringType ?? throw new ArgumentException($"{nameof(methodInfo)}.{nameof(Type.DeclaringType)} is null", nameof(methodInfo));
return GetXmlNameMethodBase(methodInfo: methodInfo);
}
/// <summary>Gets the XML name of an <see cref="ConstructorInfo"/> as it appears in the XML docs.</summary>
/// <param name="constructorInfo">The field to get the XML name of.</param>
/// <returns>The XML name of <paramref name="constructorInfo"/> as it appears in the XML docs.</returns>
public static string GetXmlName(this ConstructorInfo constructorInfo)
{
_ = constructorInfo ?? throw new ArgumentNullException(nameof(constructorInfo));
_ = constructorInfo.DeclaringType ?? throw new ArgumentException($"{nameof(constructorInfo)}.{nameof(Type.DeclaringType)} is null", nameof(constructorInfo));
return GetXmlNameMethodBase(constructorInfo: constructorInfo);
}
/// <summary>Gets the XML name of an <see cref="PropertyInfo"/> as it appears in the XML docs.</summary>
/// <param name="propertyInfo">The field to get the XML name of.</param>
/// <returns>The XML name of <paramref name="propertyInfo"/> as it appears in the XML docs.</returns>
public static string GetXmlName(this PropertyInfo propertyInfo)
{
_ = propertyInfo ?? throw new ArgumentNullException(nameof(propertyInfo));
_ = propertyInfo.DeclaringType ?? throw new ArgumentException($"{nameof(propertyInfo)}.{nameof(Type.DeclaringType)} is null", nameof(propertyInfo));
_ = propertyInfo.DeclaringType.FullName ?? throw new ArgumentException($"{nameof(propertyInfo)}.{nameof(EventInfo.DeclaringType)}.{nameof(Type.FullName)} is null", nameof(propertyInfo));
return "P:" + GetXmlNameTypeSegment(propertyInfo.DeclaringType.FullName) + "." + propertyInfo.Name;
}
/// <summary>Gets the XML name of an <see cref="FieldInfo"/> as it appears in the XML docs.</summary>
/// <param name="fieldInfo">The field to get the XML name of.</param>
/// <returns>The XML name of <paramref name="fieldInfo"/> as it appears in the XML docs.</returns>
public static string GetXmlName(this FieldInfo fieldInfo)
{
_ = fieldInfo ?? throw new ArgumentNullException(nameof(fieldInfo));
_ = fieldInfo.DeclaringType ?? throw new ArgumentException($"{nameof(fieldInfo)}.{nameof(Type.DeclaringType)} is null", nameof(fieldInfo));
_ = fieldInfo.DeclaringType.FullName ?? throw new ArgumentException($"{nameof(fieldInfo)}.{nameof(EventInfo.DeclaringType)}.{nameof(Type.FullName)} is null", nameof(fieldInfo));
return "F:" + GetXmlNameTypeSegment(fieldInfo.DeclaringType.FullName) + "." + fieldInfo.Name;
}
/// <summary>Gets the XML name of an <see cref="EventInfo"/> as it appears in the XML docs.</summary>
/// <param name="eventInfo">The event to get the XML name of.</param>
/// <returns>The XML name of <paramref name="eventInfo"/> as it appears in the XML docs.</returns>
public static string GetXmlName(this EventInfo eventInfo)
{
_ = eventInfo ?? throw new ArgumentNullException(nameof(eventInfo));
_ = eventInfo.DeclaringType ?? throw new ArgumentException($"{nameof(eventInfo)}.{nameof(Type.DeclaringType)} is null", nameof(eventInfo));
_ = eventInfo.DeclaringType.FullName ?? throw new ArgumentException($"{nameof(eventInfo)}.{nameof(EventInfo.DeclaringType)}.{nameof(Type.FullName)} is null", nameof(eventInfo));
return "E:" + GetXmlNameTypeSegment(eventInfo.DeclaringType.FullName) + "." + eventInfo.Name;
}
internal static string GetXmlNameMethodBase(MethodInfo? methodInfo = null, ConstructorInfo? constructorInfo = null)
{
if (methodInfo is not null && constructorInfo is not null)
{
throw new TowelBugException($"{nameof(GetDocumentation)} {nameof(methodInfo)} is not null && {nameof(constructorInfo)} is not null");
}
if (methodInfo is not null)
{
if (methodInfo.DeclaringType is null)
{
throw new ArgumentException($"{nameof(methodInfo)}.{nameof(Type.DeclaringType)} is null");
}
else if (methodInfo.DeclaringType.IsGenericType)
{
methodInfo = methodInfo.DeclaringType.GetGenericTypeDefinition().GetMethods(
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.NonPublic).First(x => x.MetadataToken == methodInfo.MetadataToken);
}
}
MethodBase? methodBase = methodInfo ?? (MethodBase?)constructorInfo;
_ = methodBase ?? throw new TowelBugException($"{nameof(GetDocumentation)} {nameof(methodInfo)} is null && {nameof(constructorInfo)} is null");
_ = methodBase.DeclaringType ?? throw new ArgumentException($"{nameof(methodBase)}.{nameof(Type.DeclaringType)} is null");
LoadXmlDocumentation(methodBase.DeclaringType.Assembly);
MapHashLinked<int, string, StringEquate, StringHash> typeGenericMap = new();
Type[] typeGenericArguments = methodBase.DeclaringType.GetGenericArguments();
for (int i = 0; i < typeGenericArguments.Length; i++)
{
Type typeGeneric = typeGenericArguments[i];
typeGenericMap[typeGeneric.Name] = i;
}
MapHashLinked<int, string, StringEquate, StringHash> methodGenericMap = new();
if (constructorInfo is null)
{
Type[] methodGenericArguments = methodBase.GetGenericArguments();
for (int i = 0; i < methodGenericArguments.Length; i++)
{
Type methodGeneric = methodGenericArguments[i];
methodGenericMap[methodGeneric.Name] = i;
}
}
ParameterInfo[] parameterInfos = methodBase.GetParameters();
string memberTypePrefix = "M:";
string declarationTypeString = GetXmlDocumenationFormattedString(methodBase.DeclaringType, false, typeGenericMap, methodGenericMap);
string memberNameString =
constructorInfo is not null ? "#ctor" :
methodBase.Name;
string methodGenericArgumentsString =
methodGenericMap.Count > 0 ?
"``" + methodGenericMap.Count :
string.Empty;
string parametersString =
parameterInfos.Length > 0 ?
"(" + string.Join(",", methodBase.GetParameters().Select(x => GetXmlDocumenationFormattedString(x.ParameterType, true, typeGenericMap, methodGenericMap))) + ")" :
string.Empty;
string key =
memberTypePrefix +
declarationTypeString +
"." +
memberNameString +
methodGenericArgumentsString +
parametersString;
if (methodInfo is not null &&
(methodBase.Name is "op_Implicit" ||
methodBase.Name is "op_Explicit"))
{
key += "~" + GetXmlDocumenationFormattedString(methodInfo.ReturnType, true, typeGenericMap, methodGenericMap);
}
return key;
}
internal static string GetXmlDocumenationFormattedString(
Type type,
bool isMethodParameter,
MapHashLinked<int, string, StringEquate, StringHash> typeGenericMap,
MapHashLinked<int, string, StringEquate, StringHash> methodGenericMap)
{
if (type.IsGenericParameter)
{
var (success, exception, methodIndex) = methodGenericMap.TryGet(type.Name);
return success
? "``" + methodIndex
: "`" + typeGenericMap[type.Name];
}
else if (type.HasElementType)
{
string elementTypeString = GetXmlDocumenationFormattedString(
type.GetElementType() ?? throw new ArgumentException($"{nameof(type)}.{nameof(Type.HasElementType)} && {nameof(type)}.{nameof(Type.GetElementType)}() is null", nameof(type)),
isMethodParameter,
typeGenericMap,
methodGenericMap);
switch (type)
{
case Type when type.IsPointer:
return elementTypeString + "*";
case Type when type.IsByRef:
return elementTypeString + "@";
case Type when type.IsArray:
int rank = type.GetArrayRank();
string arrayDimensionsString = rank > 1
? "[" + string.Join(",", Enumerable.Repeat("0:", rank)) + "]"
: "[]";
return elementTypeString + arrayDimensionsString;
default:
throw new TowelBugException($"{nameof(GetXmlDocumenationFormattedString)} encountered an unhandled element type: {type}");
}
}
else
{
string prefaceString = type.IsNested
? GetXmlDocumenationFormattedString(
type.DeclaringType ?? throw new ArgumentException($"{nameof(type)}.{nameof(Type.IsNested)} && {nameof(type)}.{nameof(Type.DeclaringType)} is null", nameof(type)),
isMethodParameter,
typeGenericMap,
methodGenericMap) + "."
: type.Namespace + ".";
string typeNameString = isMethodParameter
? typeNameString = Regex.Replace(type.Name, @"`\d+", string.Empty)
: typeNameString = type.Name;
string genericArgumentsString = type.IsGenericType && isMethodParameter
? "{" + string.Join(",",
type.GetGenericArguments().Select(argument =>
GetXmlDocumenationFormattedString(
argument,
isMethodParameter,
typeGenericMap,
methodGenericMap))
) + "}"
: string.Empty;
return prefaceString + typeNameString + genericArgumentsString;
}
}
internal static string GetXmlNameTypeSegment(string typeFullNameString) =>
Regex.Replace(typeFullNameString, @"\[.*\]", string.Empty).Replace('+', '.');
#endregion
#region GetXmlDocumentation
internal static object xmlCacheLock = new();
internal static ISet<Assembly> loadedAssemblies = SetHashLinked.New<Assembly>();
internal static MapHashLinked<string, string, StringEquate, StringHash> loadedXmlDocumentation = new();
internal static bool LoadXmlDocumentation(Assembly assembly)
{
if (loadedAssemblies.Contains(assembly))
{
return false;
}
bool newContent = false;
string? directoryPath = assembly.GetDirectoryPath();
if (directoryPath is not null)