-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathTypeHelper.cs
1206 lines (1060 loc) · 50.6 KB
/
TypeHelper.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
// Copyright (C) 2007-2022 Xtensive LLC.
// This code is distributed under MIT license terms.
// See the License.txt file in the project root for more information.
// Created by: Nick Svetlov
// Created: 2007.06.13
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using Xtensive.Collections;
using System.Linq;
using Xtensive.Core;
using Xtensive.Sorting;
using JetBrains.Annotations;
namespace Xtensive.Reflection
{
/// <summary>
/// <see cref="Type"/> related helper \ extension methods.
/// </summary>
public static class TypeHelper
{
private class TypesEqualityComparer : IEqualityComparer<(Type, Type[])>
{
public bool Equals((Type, Type[]) x, (Type, Type[]) y) =>
x.Item1 == y.Item1 && x.Item2.SequenceEqual(y.Item2);
public int GetHashCode((Type, Type[]) obj)
{
var hash = obj.Item1.GetHashCode();
for (int i = obj.Item2.Length; i-- > 0;) {
hash = HashCode.Combine(hash, obj.Item2[i]);
}
return hash;
}
}
private const string InvokeMethodName = "Invoke";
private static readonly object EmitLock = new object();
private static readonly int NullableTypeMetadataToken = WellKnownTypes.NullableOfT.MetadataToken;
private static readonly int ValueTuple1 = typeof(ValueTuple<>).MetadataToken;
private static readonly int ValueTuple8 = typeof(ValueTuple<,,,,,,,>).MetadataToken;
private static readonly Module SystemCoreLibModule = WellKnownTypes.NullableOfT.Module;
private static readonly Type CompilerGeneratedAttributeType = typeof(CompilerGeneratedAttribute);
private static readonly string TypeHelperNamespace = typeof(TypeHelper).Namespace;
private static readonly ConcurrentDictionary<(Type, Type[]), ConstructorInfo> ConstructorInfoByTypes =
new(new TypesEqualityComparer());
private static readonly ConcurrentDictionary<Type, Type[]> OrderedInterfaces = new();
private static readonly ConcurrentDictionary<Type, Type[]> UnorderedInterfaces = new();
private static readonly ConcurrentDictionary<Type, Type[]> OrderedCompatibles = new();
private static readonly ConcurrentDictionary<(Type, Type), InterfaceMapping> interfaceMaps = new();
private static readonly ConcurrentDictionary<(MethodInfo, Type), MethodInfo> GenericMethodInstances1 = new();
private static readonly ConcurrentDictionary<(MethodInfo, Type, Type), MethodInfo> GenericMethodInstances2 = new();
private static readonly ConcurrentDictionary<(Type, Type), Type> GenericTypeInstances1 = new();
private static readonly ConcurrentDictionary<(Type, Type, Type), Type> GenericTypeInstances2 = new();
private static readonly Func<(MethodInfo genericDefinition, Type typeArgument), MethodInfo> GenericMethodFactory1 =
key => key.genericDefinition.MakeGenericMethod(key.typeArgument);
private static readonly Func<(MethodInfo genericDefinition, Type typeArgument1, Type typeArgument2), MethodInfo> GenericMethodFactory2 =
key => key.genericDefinition.MakeGenericMethod(key.typeArgument1, key.typeArgument2);
private static readonly Func<(Type genericDefinition, Type typeArgument), Type> GenericTypeFactory1 = key =>
key.genericDefinition.MakeGenericType(key.typeArgument);
private static readonly Func<(Type genericDefinition, Type typeArgument1, Type typeArgument2), Type> GenericTypeFactory2 = key =>
key.genericDefinition.MakeGenericType(key.typeArgument1, key.typeArgument2);
private static readonly ConcurrentDictionary<(Type Type, bool UseShortForm), string> MemoizedTypeNames = new();
private static int createDummyTypeNumber = 0;
private static AssemblyBuilder assemblyBuilder;
private static ModuleBuilder moduleBuilder;
/// <summary>
/// Searches for associated class for <paramref name="forType"/>, creates its instance, if found.
/// Otherwise returns <see langword="null"/>.
/// </summary>
/// <typeparam name="T">Type of result. Can be ether class or interface.</typeparam>
/// <param name="forType">Type to search the associate for.</param>
/// <param name="foundForType">Type the associate was found for.</param>
/// <param name="associateTypeSuffixes">Associate type name suffix.</param>
/// <param name="constructorParams">Parameters to pass to associate constructor.</param>
/// <returns>Newly created associate for <paramref name="forType"/>, if found;
/// otherwise, <see langword="null"/>.</returns>
public static T CreateAssociate<T>(Type forType, out Type foundForType, string[] associateTypeSuffixes,
object[] constructorParams)
where T : class =>
CreateAssociate<T>(forType, out foundForType, associateTypeSuffixes, constructorParams,
Array.Empty<Pair<Assembly, string>>());
/// <summary>
/// Searches for associated class for <paramref name="forType"/>, creates its instance, if found.
/// Otherwise returns <see langword="null"/>.
/// </summary>
/// <typeparam name="T">Type of result. Can be ether class or interface.</typeparam>
/// <param name="forType">Type to search the associate for.</param>
/// <param name="foundForType">Type the associate was found for.</param>
/// <param name="associateTypeSuffixes">Associate type name suffix.</param>
/// <param name="highPriorityLocations">High-priority search locations (assembly + namespace pairs).</param>
/// <param name="constructorParams">Parameters to pass to associate constructor.</param>
/// <returns>Newly created associate for <paramref name="forType"/>, if found;
/// otherwise, <see langword="null"/>.</returns>
public static T CreateAssociate<T>(Type forType, out Type foundForType, string[] associateTypeSuffixes,
object[] constructorParams, IEnumerable<Pair<Assembly, string>> highPriorityLocations)
where T : class =>
CreateAssociate<T>(forType, out foundForType, associateTypeSuffixes, constructorParams, highPriorityLocations,
false);
/// <summary>
/// Searches for associated class for <paramref name="forType"/>, creates its instance, if found.
/// Otherwise returns <see langword="null"/>.
/// </summary>
/// <typeparam name="T">Type of result. Can be ether class or interface.</typeparam>
/// <param name="forType">Type to search the associate for.</param>
/// <param name="foundForType">Type the associate was found for.</param>
/// <param name="associateTypeSuffixes">Associate type name suffix.</param>
/// <param name="highPriorityLocations">High-priority search locations (assembly + namespace pairs).</param>
/// <param name="constructorParams">Parameters to pass to associate constructor.</param>
/// <returns>Newly created associate for <paramref name="forType"/>, if found;
/// otherwise, <see langword="null"/>.</returns>
/// <param name="exactTypeMatch">If <see langword="false"/> tries to create associates for base class, interfaces,
/// arrays and <see cref="Nullable{T}"/>(if struct) too.</param>
/// <exception cref="InvalidOperationException"><paramref name="forType"/> is generic type definition.</exception>
public static T CreateAssociate<T>(Type forType, out Type foundForType, string[] associateTypeSuffixes,
object[] constructorParams, IEnumerable<Pair<Assembly, string>> highPriorityLocations, bool exactTypeMatch)
where T : class
{
ArgumentValidator.EnsureArgumentNotNull(forType, nameof(forType));
if (forType.IsGenericTypeDefinition) {
throw new InvalidOperationException(string.Format(
Strings.ExCantCreateAssociateForGenericTypeDefinitions, GetShortName(forType)));
}
var locations = new List<Pair<Assembly, string>>(1);
if (highPriorityLocations != null) {
locations.AddRange(highPriorityLocations);
}
return
CreateAssociateInternal<T>(forType, forType, out foundForType, associateTypeSuffixes, constructorParams,
locations, exactTypeMatch);
}
private static T CreateAssociateInternal<T>(Type originalForType, Type currentForType, out Type foundForType,
string[] associateTypeSuffixes, object[] constructorParams, List<Pair<Assembly, string>> locations,
bool exactTypeMatch)
where T : class
{
if (currentForType == null) {
foundForType = null;
return null;
}
string associateTypePrefix;
Type[] genericArguments;
// Possible cases: generic type, array type, regular type
if (currentForType.IsGenericType) {
// Generic type
associateTypePrefix = currentForType.Name;
genericArguments = currentForType.GetGenericArguments();
}
else if (currentForType.IsArray) {
// Array type
var elementType = currentForType.GetElementType();
var rank = currentForType.GetArrayRank();
associateTypePrefix = rank == 1 ? "Array`1" : $"Array{rank}D`1";
genericArguments = new[] { elementType };
}
else if (currentForType == WellKnownTypes.Enum) {
// Enum type
var underlyingType = Enum.GetUnderlyingType(originalForType);
associateTypePrefix = "Enum`2";
genericArguments = new[] { originalForType, underlyingType };
}
else if (currentForType == WellKnownTypes.Array) {
// Untyped Array type
foundForType = null;
return null;
}
else {
// Regular type
associateTypePrefix = currentForType.Name;
genericArguments = null;
}
// Replacing 'I' at interface types
if (currentForType.IsInterface && associateTypePrefix.StartsWith("I", StringComparison.Ordinal)) {
associateTypePrefix = AddSuffix(associateTypePrefix.Substring(1), "Interface");
}
// Search for exact associate
var result = CreateAssociateInternal<T>(originalForType, currentForType, out foundForType, associateTypePrefix,
associateTypeSuffixes, locations, genericArguments, constructorParams);
if (result != null) {
return result;
}
if (exactTypeMatch) {
foundForType = null;
return null;
}
// Nothing is found; trying to find an associate for base type (except Object)
var forTypeBase = currentForType.BaseType;
if (forTypeBase != null) {
while (forTypeBase != null && forTypeBase != WellKnownTypes.Object) {
result = CreateAssociateInternal<T>(originalForType, forTypeBase, out foundForType,
associateTypeSuffixes, constructorParams, locations, true);
if (result != null) {
return result;
}
forTypeBase = forTypeBase.BaseType;
}
}
// Nothing is found; trying to find an associate for implemented interface
var interfaces = GetInterfacesUnordered(currentForType).ToArray();
var interfaceCount = interfaces.Length;
var suppressed = new BitArray(interfaceCount);
while (interfaceCount > 0) {
// Suppressing all the interfaces inherited from others
// to allow their associates to not conflict with each other
for (var i = 0; i < interfaceCount; i++) {
for (var j = 0; j < interfaceCount; j++) {
if (i == j || !interfaces[i].IsAssignableFrom(interfaces[j])) {
continue;
}
suppressed[i] = true;
break;
}
}
Type lastGoodInterfaceType = null;
// Scanning non-suppressed interfaces
for (var i = 0; i < interfaceCount; i++) {
if (suppressed[i]) {
continue;
}
var resultForInterface = CreateAssociateInternal<T>(originalForType, interfaces[i], out foundForType,
associateTypeSuffixes, constructorParams, locations, true);
if (resultForInterface == null) {
continue;
}
if (result != null) {
throw new InvalidOperationException(string.Format(
Strings.ExMultipleAssociatesMatch,
GetShortName(currentForType),
GetShortName(result.GetType()),
GetShortName(resultForInterface.GetType())));
}
result = resultForInterface;
lastGoodInterfaceType = foundForType;
foundForType = null;
}
if (result != null) {
foundForType = lastGoodInterfaceType;
return result;
}
// Moving suppressed interfaces to the beginning
// to scan them on the next round
var k = 0;
for (var i = 0; i < interfaceCount; i++) {
if (suppressed[i]) {
interfaces[k] = interfaces[i];
suppressed[k] = false;
k++;
}
}
interfaceCount = k;
}
// Nothing is found; trying to find an associate for Object type
if (currentForType != WellKnownTypes.Object) {
result = CreateAssociateInternal<T>(originalForType, WellKnownTypes.Object, out foundForType,
"Object", associateTypeSuffixes,
locations, null, constructorParams);
if (result != null) {
return result;
}
}
// Nothing is found at all
foundForType = null;
return null;
}
private static T CreateAssociateInternal<T>(Type originalForType,
Type currentForType,
out Type foundForType,
string associateTypePrefix,
string[] associateTypeSuffixes,
List<Pair<Assembly, string>> locations,
Type[] genericArguments,
object[] constructorParams)
where T : class
{
var newLocationCount = 0;
var pair = new Pair<Assembly, string>(typeof(T).Assembly, typeof(T).Namespace);
if (locations.FindIndex(p => p.First == pair.First && p.Second == pair.Second) < 0) {
locations.Add(pair);
newLocationCount++;
}
pair = new Pair<Assembly, string>(currentForType.Assembly, currentForType.Namespace);
if (locations.FindIndex(p => p.First == pair.First && p.Second == pair.Second) < 0) {
locations.Add(pair);
newLocationCount++;
}
try {
for (int i = 0, count = locations.Count; i < count; i++) {
var location = locations[i];
for (var currentSuffix = 0; currentSuffix < associateTypeSuffixes.Length; currentSuffix++) {
var associateTypeSuffix = associateTypeSuffixes[currentSuffix];
// Trying exact type match (e.g. EnumerableInterfaceHandler`1<...>)
var associateTypeName = AddSuffix($"{location.Second}.{associateTypePrefix}", associateTypeSuffix);
var suffix = CorrectGenericSuffix(associateTypeName, genericArguments?.Length ?? 0);
if (Activate(location.First, suffix, genericArguments, constructorParams) is T result) {
foundForType = currentForType;
return result;
}
// Trying to paste original type as generic parameter
suffix = CorrectGenericSuffix(associateTypeName, 1);
result = Activate(location.First, suffix, new[] { originalForType }, constructorParams) as T;
if (result != null) {
foundForType = currentForType;
return result;
}
// Trying a generic one (e.g. EnumerableInterfaceHandler`2<T, ...>)
Type[] newGenericArguments;
if (genericArguments == null || genericArguments.Length == 0) {
newGenericArguments = new[] { originalForType };
associateTypeName = AddSuffix($"{location.Second}.{associateTypePrefix}`1", associateTypeSuffix);
}
else {
newGenericArguments = new Type[genericArguments.Length + 1];
newGenericArguments[0] = originalForType;
Array.Copy(genericArguments, 0, newGenericArguments, 1, genericArguments.Length);
associateTypeName = AddSuffix(
$"{location.Second}.{TrimGenericSuffix(associateTypePrefix)}`{newGenericArguments.Length}",
associateTypeSuffix);
}
suffix = CorrectGenericSuffix(associateTypeName, newGenericArguments.Length);
result = Activate(location.First, suffix, newGenericArguments, constructorParams) as T;
if (result != null) {
foundForType = currentForType;
return result;
}
}
}
foundForType = null;
return null;
}
finally {
for (var i = 0; i < newLocationCount; i++) {
locations.RemoveAt(locations.Count - 1);
}
}
}
/// <summary>
/// Creates new dummy type. Such types can be used
/// as generic arguments (to instantiate unique generic
/// instances).
/// </summary>
/// <param name="namePrefix">Prefix to include into type name.</param>
/// <param name="inheritFrom">The type to inherit the dummy type from.</param>
/// <param name="implementProtectedConstructorAccessor">If <see langword="true"/>, static method with name
/// <see cref="DelegateHelper.AspectedFactoryMethodName"/> will be created for each constructor.</param>
/// <returns><see cref="Type"/> object of newly created type.</returns>
public static Type CreateDummyType(string namePrefix, Type inheritFrom, bool implementProtectedConstructorAccessor)
{
ArgumentValidator.EnsureArgumentNotNullOrEmpty(namePrefix, nameof(namePrefix));
ArgumentValidator.EnsureArgumentNotNull(inheritFrom, nameof(inheritFrom));
var n = Interlocked.Increment(ref createDummyTypeNumber);
var typeName = $"{TypeHelperNamespace}.Internal.{namePrefix}{n}";
return CreateInheritedDummyType(typeName, inheritFrom, implementProtectedConstructorAccessor);
}
/// <summary>
/// Creates new dummy type inherited from another type.
/// </summary>
/// <param name="typeName">Type name.</param>
/// <param name="inheritFrom">The type to inherit the dummy type from.</param>
/// <param name="implementProtectedConstructorAccessor">If <see langword="true"/>, static method with name
/// <see cref="DelegateHelper.AspectedFactoryMethodName"/> will be created for each constructor.</param>
/// <returns>New type.</returns>
public static Type CreateInheritedDummyType(string typeName, Type inheritFrom,
bool implementProtectedConstructorAccessor)
{
ArgumentValidator.EnsureArgumentNotNullOrEmpty(typeName, nameof(typeName));
ArgumentValidator.EnsureArgumentNotNull(inheritFrom, nameof(inheritFrom));
EnsureEmitInitialized();
lock (EmitLock) {
var typeBuilder = moduleBuilder.DefineType(
typeName,
TypeAttributes.Public | TypeAttributes.Sealed,
inheritFrom,
Array.Empty<Type>()
);
const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
foreach (var baseConstructor in inheritFrom.GetConstructors(bindingFlags)) {
var parameters = baseConstructor.GetParameters();
var parameterTypes = new Type[parameters.Length];
for (var index = 0; index < parameters.Length; index++) {
parameterTypes[index] = parameters[index].ParameterType;
}
var constructorBuilder = typeBuilder.DefineConstructor(
baseConstructor.Attributes,
CallingConventions.Standard,
parameterTypes
);
// Create constructor
var constructorIlGenerator = constructorBuilder.GetILGenerator();
constructorIlGenerator.Emit(OpCodes.Ldarg_0);
var parametersCount = parameterTypes.Length;
for (short i = 1; i <= parametersCount; i++) {
constructorIlGenerator.Emit(OpCodes.Ldarg, i);
}
constructorIlGenerator.Emit(OpCodes.Call, baseConstructor);
constructorIlGenerator.Emit(OpCodes.Ret);
// Create ProtectedConstructorAccessor
if (implementProtectedConstructorAccessor) {
var methodBuilder = typeBuilder.DefineMethod(DelegateHelper.AspectedFactoryMethodName,
MethodAttributes.Private | MethodAttributes.Static,
CallingConventions.Standard, typeBuilder.UnderlyingSystemType, parameterTypes);
var accessorIlGenerator = methodBuilder.GetILGenerator();
for (short i = 0; i < parameterTypes.Length; i++) {
accessorIlGenerator.Emit(OpCodes.Ldarg, i);
}
accessorIlGenerator.Emit(OpCodes.Newobj, constructorBuilder);
accessorIlGenerator.Emit(OpCodes.Ret);
}
}
return typeBuilder.CreateTypeInfo().AsType();
}
}
private static void EnsureEmitInitialized()
{
if (moduleBuilder != null) {
return;
}
lock (EmitLock) {
if (moduleBuilder != null) {
return;
}
var assemblyName = new AssemblyName("Xtensive.TypeHelper.GeneratedTypes");
assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
var tmp = assemblyBuilder.DefineDynamicModule(assemblyName.Name);
Thread.MemoryBarrier();
moduleBuilder = tmp;
}
}
/// <summary>
/// Adds suffix to specified generic type name.
/// </summary>
/// <param name="typeName">Type name to add suffix for.</param>
/// <param name="suffix">Suffix to add.</param>
/// <returns>Specified generic type name with its suffix.</returns>
public static string AddSuffix(string typeName, string suffix)
{
var i = typeName.IndexOf('`');
if (i >= 0) {
return typeName.Substring(0, i) + suffix + typeName.Substring(i);
}
i = typeName.IndexOf('<');
if (i >= 0) {
return typeName.Substring(0, i) + suffix + typeName.Substring(i);
}
return typeName + suffix;
}
/// <summary>
/// Instantiates specified generic type; returns <see langword="null"/>, if either no such a type,
/// or an error has occurred.
/// </summary>
/// <param name="assembly">Assembly where the type is located.</param>
/// <param name="typeName">Name of the type to instantiate.</param>
/// <param name="genericArguments">Generic arguments for the type to instantiate
/// (<see langword="null"/> means type isn't a generic type definition).</param>
/// <param name="arguments">Arguments to pass to the type constructor.</param>
/// <returns>An instance of specified type; <see langword="null"/>, if either no such a type,
/// or an error has occurred.</returns>
public static object Activate(Assembly assembly, string typeName, Type[] genericArguments,
params object[] arguments)
{
ArgumentValidator.EnsureArgumentNotNull(assembly, nameof(assembly));
ArgumentValidator.EnsureArgumentNotNullOrEmpty(typeName, nameof(typeName));
var type = assembly.GetType(typeName, false);
return type == null ? null : Activate(type, genericArguments, arguments);
}
/// <summary>
/// Instantiates specified generic type; returns <see langword="null"/>, if either no such a type,
/// or an error has occurred.
/// </summary>
/// <param name="type">Generic type definition to instantiate.</param>
/// <param name="genericArguments">Generic arguments for the type to instantiate
/// (<see langword="null"/> means <paramref name="type"/> isn't a generic type definition).</param>
/// <param name="arguments">Arguments to pass to the type constructor.</param>
/// <returns>An instance of specified type; <see langword="null"/>, if either no such a type,
/// or an error has occurred.</returns>
[DebuggerStepThrough]
public static object Activate(this Type type, Type[] genericArguments, params object[] arguments)
{
try {
if (type.IsAbstract) {
return null;
}
if (type.IsGenericTypeDefinition ^ (genericArguments != null)) {
return null;
}
if (type.IsGenericTypeDefinition) {
if (genericArguments == null) {
genericArguments = Array.Empty<Type>();
}
var genericParameters = type.GetGenericArguments();
if (genericParameters.Length != genericArguments.Length) {
return null;
}
var genericParameterIndexes = genericParameters
.Select((parameter, index) => (parameter, index))
.ToDictionary(a => a.parameter, a => a.index);
for (var i = 0; i < genericParameters.Length; i++) {
var parameter = genericParameters[i];
var constraints = parameter.GetGenericParameterConstraints();
var argument = genericArguments[i];
foreach (var constraint in constraints) {
var projectedConstraint = constraint;
if (constraint.IsGenericParameter) {
projectedConstraint = genericArguments[genericParameterIndexes[constraint]];
}
else if (constraint.IsGenericType) {
var constraintArguments = constraint.GetGenericArguments();
var projectedConstraintArguments = new Type[constraintArguments.Length];
for (var j = 0; j < constraintArguments.Length; j++) {
projectedConstraintArguments[j] =
genericParameterIndexes.TryGetValue(constraintArguments[j], out var index)
? genericArguments[index]
: constraintArguments[j];
}
projectedConstraint = constraint
.GetGenericTypeDefinition()
.MakeGenericType(projectedConstraintArguments);
}
if (!projectedConstraint.IsAssignableFrom(argument)) {
return null;
}
}
}
type = type.MakeGenericType(genericArguments);
}
if (arguments == null) {
arguments = Array.Empty<object>();
}
const BindingFlags bindingFlags =
BindingFlags.CreateInstance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
var argumentTypes = new object[arguments.Length];
for (var i = 0; i < arguments.Length; i++) {
var o = arguments[i];
if (o == null) {
// Actually a case when GetConstructor will fail,
// so we should fall back to Activator.CreateInstance
return Activator.CreateInstance(type, bindingFlags, null, arguments, null);
}
argumentTypes[i] = o.GetType();
}
var constructor = type.GetConstructorEx(bindingFlags, argumentTypes);
return constructor == null ? null : constructor.Invoke(arguments);
}
catch (Exception) {
return null;
}
}
/// <summary>
/// Gets the public constructor of type <paramref name="type"/>
/// accepting specified <paramref name="arguments"/>.
/// </summary>
/// <param name="type">The type to get the constructor for.</param>
/// <param name="arguments">The arguments.</param>
/// <returns>
/// Appropriate constructor, if a single match is found;
/// otherwise, <see langword="null"/>.
/// </returns>
[Obsolete, CanBeNull]
public static ConstructorInfo GetConstructor(this Type type, object[] arguments) =>
GetSingleConstructorOrDefault(type, arguments.Select(a => a?.GetType()).ToArray());
/// <summary>
/// Gets the public constructor of type <paramref name="type"/>
/// accepting specified <paramref name="argumentTypes"/>.
/// </summary>
/// <param name="type">The type to get the constructor for.</param>
/// <param name="argumentTypes">The arguments.</param>
/// <returns>
/// Appropriate constructor, if a single match is found;
/// otherwise throws <see cref="InvalidOperationException"/>.
/// </returns>
/// <exception cref="InvalidOperationException">
/// The <paramref name="type"/> has no constructors suitable for <paramref name="argumentTypes"/>
/// -or- more than one such constructor.
/// </exception>
public static ConstructorInfo GetSingleConstructor(this Type type, Type[] argumentTypes) =>
ConstructorInfoByTypes.GetOrAdd((type, argumentTypes), ConstructorExtractor)
?? throw new InvalidOperationException(Strings.ExGivenTypeHasNoOrMoreThanOneCtorWithGivenParameters);
/// <summary>
/// Gets the public constructor of type <paramref name="type"/>
/// accepting specified <paramref name="argumentTypes"/>.
/// </summary>
/// <param name="type">The type to get the constructor for.</param>
/// <param name="argumentTypes">The arguments.</param>
/// <returns>
/// Appropriate constructor, if a single match is found;
/// otherwise, <see langword="null"/>.
/// </returns>
[CanBeNull]
public static ConstructorInfo GetSingleConstructorOrDefault(this Type type, Type[] argumentTypes) =>
ConstructorInfoByTypes.GetOrAdd((type, argumentTypes), ConstructorExtractor);
private static readonly Func<(Type, Type[]), ConstructorInfo> ConstructorExtractor = t => {
(var type, var argumentTypes) = t;
var constructors =
from ctor in type.GetConstructors()
let parameters = ctor.GetParameters()
where parameters.Length == argumentTypes.Length
let zipped = parameters.Zip(argumentTypes, (parameter, argumentType) => (parameter, argumentType))
where (
from pair in zipped
let parameter = pair.parameter
let parameterType = parameter.ParameterType
let argumentType = pair.argumentType
select
!parameter.IsOut && (
parameterType.IsAssignableFrom(argumentType ?? WellKnownTypes.Object) ||
(!parameterType.IsValueType && argumentType == null) ||
(parameterType.IsNullable() && argumentType == null)
)
).All(passed => passed)
select ctor;
return constructors.SingleOrDefault();
};
/// <summary>
/// Orders the specified <paramref name="types"/> by their inheritance
/// (very base go first).
/// </summary>
/// <param name="types">The types to sort.</param>
/// <returns>The list of <paramref name="types"/> ordered by their inheritance.</returns>
public static IEnumerable<Type> OrderByInheritance(this IEnumerable<Type> types) =>
TopologicalSorter.Sort(types, static (t1, t2) => t1.IsAssignableFrom(t2));
/// <summary>
/// Fast analogue of <see cref="Type.GetInterfaceMap"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="targetInterface">The target interface.</param>
/// <returns>Interface map for the specified interface.</returns>
public static InterfaceMapping GetInterfaceMapFast(this Type type, Type targetInterface) =>
interfaceMaps.GetOrAdd((type, targetInterface), static pair => new InterfaceMapping(pair.Item1.GetInterfaceMap(pair.Item2)));
/// <summary>
/// Gets the interfaces of the specified type.
/// Interfaces will be unordered.
/// </summary>
/// <param name="type">The type to get the interfaces of.</param>
public static IReadOnlyList<Type> GetInterfacesUnordered(Type type) =>
UnorderedInterfaces.GetOrAdd(type, static t => t.GetInterfaces());
/// <summary>
/// Gets the interfaces of the specified type.
/// Interfaces will be ordered from the very base ones to ancestors.
/// </summary>
/// <param name="type">The type to get the interfaces of.</param>
[Obsolete("Use GetInterfacesOrderByInheritance instead")]
public static Type[] GetInterfaces(this Type type) =>
OrderedInterfaces.GetOrAdd(type, t => t.GetInterfaces().OrderByInheritance().ToArray());
/// <summary>
/// Gets the interfaces of the specified type.
/// Interfaces will be ordered from the very base ones to ancestors.
/// </summary>
/// <param name="type">The type to get the interfaces of.</param>
public static Type[] GetInterfacesOrderedByInheritance(this Type type) =>
OrderedInterfaces.GetOrAdd(type, t => t.GetInterfaces().OrderByInheritance().ToArray());
/// <summary>
/// Gets the sequence of type itself, all its base types and interfaces.
/// Types will be ordered from the very base ones to ancestors with the specified type in the end of sequence.
/// </summary>
/// <param name="type">The type to get compatible types for.</param>
/// <returns>The interfaces of the specified type.</returns>
public static Type[] GetCompatibles(this Type type) =>
OrderedCompatibles.GetOrAdd(type,
t => {
var interfaces = GetInterfacesUnordered(t);
var bases = EnumerableUtils.Unfold(t.BaseType, baseType => baseType.BaseType);
return bases
.Concat(interfaces)
.OrderByInheritance()
.Append(t)
.ToArray();
});
/// <summary>
/// Builds correct full generic type name.
/// </summary>
/// <param name="type">A <see cref="Type"/> which name is built.</param>
/// <returns>Full type name.</returns>
public static string GetFullName(this Type type)
{
if (type == null) {
return null;
}
if (type.IsGenericParameter) {
return type.Name;
}
var declaringType = type.DeclaringType;
if (declaringType == null) {
return type.InnerGetTypeName(useShortForm: false);
}
if (declaringType.IsGenericTypeDefinition) {
declaringType =
declaringType.MakeGenericType(
type.GetGenericArguments()
.Take(declaringType.GetGenericArguments().Length)
.ToArray());
}
return $"{declaringType.GetFullName()}+{type.InnerGetTypeName(useShortForm: false)}";
}
/// <summary>
/// Builds correct short generic type name (without namespaces).
/// </summary>
/// <param name="type">A <see cref="Type"/> which name is built.</param>
/// <returns>Short type name.</returns>
public static string GetShortName(this Type type)
{
if (type == null) {
return null;
}
if (type.IsGenericParameter) {
return type.Name;
}
var declaringType = type.DeclaringType;
if (declaringType == null) {
return type.InnerGetTypeName(useShortForm: true);
}
if (declaringType.IsGenericTypeDefinition) {
declaringType =
declaringType.MakeGenericType(
type.GetGenericArguments()
.Take(declaringType.GetGenericArguments().Length)
.ToArray());
}
return $"{declaringType.GetShortName()}+{type.InnerGetTypeName(useShortForm: true)}";
}
private static string InnerGetTypeName(this Type type, bool useShortForm) =>
MemoizedTypeNames.GetOrAdd((type, useShortForm), TypeNameFactory);
private static readonly Func<(Type Type, bool UseShortForm), string> TypeNameFactory = t => {
var (type, useShortForm) = t;
var result = useShortForm || type.DeclaringType != null // Is nested
? type.Name
: $"{type.Namespace}.{type.Name}";
var arrayBracketPosition = result.IndexOf('[');
if (arrayBracketPosition > 0) {
result = result.Substring(0, arrayBracketPosition);
}
var arguments = type.GetGenericArguments();
if (arguments.Length > 0) {
if (type.DeclaringType != null) {
arguments = arguments
.Skip(type.DeclaringType.GetGenericArguments().Length)
.ToArray();
}
var sb = new StringBuilder().Append(TrimGenericSuffix(result)).Append('<');
char? comma = default;
foreach (var argument in arguments) {
if (comma.HasValue) {
_ = sb.Append(comma.Value);
}
if (!type.IsGenericTypeDefinition) {
_ = sb.Append(InnerGetTypeName(argument, useShortForm));
}
comma = ',';
}
_ = sb.Append('>');
result = sb.ToString();
}
if (type.IsArray) {
var sb = new StringBuilder(result);
var elementType = type;
while (elementType?.IsArray == true) {
_ = sb.Append('[');
var commaCount = elementType.GetArrayRank() - 1;
for (var i = 0; i < commaCount; i++) {
_ = sb.Append(',');
}
_ = sb.Append(']');
elementType = elementType.GetElementType();
}
result = sb.ToString();
}
return result;
};
/// <summary>
/// Indicates whether <paramref name="type"/> is a <see cref="Nullable{T}"/> type.
/// </summary>
/// <param name="type">Type to check.</param>
/// <returns><see langword="True"/> if type is nullable type;
/// otherwise, <see langword="false"/>.</returns>
public static bool IsNullable(this Type type) =>
(type.MetadataToken ^ NullableTypeMetadataToken) == 0 && ReferenceEquals(type.Module, SystemCoreLibModule);
/// <summary>
/// Indicates whether <typeparamref name="T"/> type is a <see cref="Nullable{T}"/> type.
/// </summary>
/// <typeparam name="T">Type to check.</typeparam>
/// <returns><see langword="True"/> if type is nullable type;
/// otherwise, <see langword="false"/>.</returns>
public static bool IsNullable<T>() => typeof(T).IsNullable();
/// <summary>
/// Indicates whether <paramref name="type"/> is a final type.
/// </summary>
/// <param name="type">Type to check.</param>
/// <returns><see langword="True"/> if type is final type;
/// otherwise, <see langword="false"/>.</returns>
public static bool IsFinal(this Type type) => type.IsValueType || type.IsSealed;
/// <summary>
/// Indicates whether <typeparamref name="T"/> type is a final type.
/// </summary>
/// <typeparam name="T">Type to check.</typeparam>
/// <returns><see langword="True"/> if type is final type;
/// otherwise, <see langword="false"/>.</returns>
public static bool IsFinal<T>() => IsFinal(typeof(T));
/// <summary>
/// Gets the delegate "Invoke" method (describing the delegate) for
/// the specified <paramref name="delegateType"/>.
/// </summary>
/// <param name="delegateType">Type of the delegate to get the "Invoke" method of.</param>
/// <returns><see cref="MethodInfo"/> object describing the delegate "Invoke" method.</returns>
public static MethodInfo GetInvokeMethod(this Type delegateType) => delegateType.GetMethod(InvokeMethodName);
/// <summary>
/// Determines whether given <paramref name="method"/> is a specification
/// of the provided <paramref name="genericMethodDefinition"/>.
/// </summary>
/// <param name="method">The <see cref="MethodInfo"/> to check.</param>
/// <param name="genericMethodDefinition">The <see cref="MethodInfo"/> of the generic method definition
/// to check against.</param>
/// <returns><see langword="true"/> if the specified <paramref name="method"/> is a specification
/// of the provided <paramref name="genericMethodDefinition"/>.</returns>
public static bool IsGenericMethodSpecificationOf(this MethodInfo method, MethodInfo genericMethodDefinition) =>
method.MetadataToken == genericMethodDefinition.MetadataToken
&& (ReferenceEquals(method.Module, genericMethodDefinition.Module)
|| method.Module == genericMethodDefinition.Module)
&& method.IsGenericMethod && genericMethodDefinition.IsGenericMethodDefinition;
public static MethodInfo CachedMakeGenericMethod(this MethodInfo genericDefinition, Type typeArgument) =>
GenericMethodInstances1.GetOrAdd((genericDefinition, typeArgument), GenericMethodFactory1);
public static MethodInfo CachedMakeGenericMethod(this MethodInfo genericDefinition, Type typeArgument1, Type typeArgument2) =>
GenericMethodInstances2.GetOrAdd((genericDefinition, typeArgument1, typeArgument2), GenericMethodFactory2);
public static Type CachedMakeGenericType(this Type genericDefinition, Type typeArgument) =>
GenericTypeInstances1.GetOrAdd((genericDefinition, typeArgument), GenericTypeFactory1);
public static Type CachedMakeGenericType(this Type genericDefinition, Type typeArgument1, Type typeArgument2) =>
GenericTypeInstances2.GetOrAdd((genericDefinition, typeArgument1, typeArgument2), GenericTypeFactory2);
/// <summary>
/// Determines whether the specified <paramref name="type"/> is an ancestor or an instance of the
/// provided <paramref name="openGenericBaseType"/>.
/// </summary>
/// <param name="type">The type to check.</param>
/// <param name="openGenericBaseType">Type of the generic. It is supposed this is an open generic type.</param>
/// <returns>
/// <see langword="true"/> if the specified <paramref name="type"/> is an ancestor or an instance of the
/// provided <paramref name="openGenericBaseType"/>; otherwise, <see langword="false"/>.
/// </returns>
public static bool IsOfGenericType(this Type type, Type openGenericBaseType) =>
GetGenericType(type, openGenericBaseType) != null;
/// <summary>
/// Determines whether the specified <paramref name="type"/> is an ancestor or an instance of
/// the provided <paramref name="openGenericBaseType"/> and returns closed generic type with the
/// specified type arguments if found.
/// </summary>
/// <param name="type">The type to check.</param>
/// <param name="openGenericBaseType">Open generic type to be matched.</param>
/// <returns>
/// A <see cref="Type"/> representing the closed generic version of <paramref name="openGenericBaseType"/>
/// where type parameters are bound in case it exists in <paramref name="type"/>'s inheritance hierarchy;
/// otherwise, <see langword="null"/>.
/// </returns>
public static Type GetGenericType(this Type type, Type openGenericBaseType)
{
var definitionMetadataToken = openGenericBaseType.MetadataToken;
var definitionModule = openGenericBaseType.Module;
while (type != null && !ReferenceEquals(type, WellKnownTypes.Object)) {
if ((type.MetadataToken ^ definitionMetadataToken) == 0 && ReferenceEquals(type.Module, definitionModule)) {
return type;
}
type = type.BaseType;
}
return null;
}
/// <summary>
/// Determines whether specified <paramref name="type"/> is an implementation of the
/// provided <paramref name="openGenericInterface"/>.
/// </summary>
/// <param name="type">A <see cref="Type"/> instance to be checked.</param>
/// <param name="openGenericInterface">A <see cref="Type"/> of an open generic <see langword="interface"/>
/// to match the specified <paramref name="type"/> against.</param>