-
Notifications
You must be signed in to change notification settings - Fork 161
Expand file tree
/
Copy pathTypeHelpers.cs
More file actions
1459 lines (1206 loc) · 54 KB
/
TypeHelpers.cs
File metadata and controls
1459 lines (1206 loc) · 54 KB
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) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.ClearScript.Util.COM;
namespace Microsoft.ClearScript.Util
{
internal static partial class TypeHelpers
{
private static readonly string[] importDenyList =
{
// ReSharper disable StringLiteralTypo
"FXAssembly",
"ThisAssembly",
"AssemblyRef",
"SRETW",
"MatchState",
"__DynamicallyInvokableAttribute"
// ReSharper restore StringLiteralTypo
};
private static readonly ConcurrentDictionary<Tuple<Type, BindingFlags, Type, ScriptAccess, bool>, Invocability> invocabilityMap = new();
private static readonly NumericTypes[] numericConversions =
{
// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/numeric-conversions
// IMPORTANT: maintain NumericType order
/* None */ NumericTypes.None,
/* Char */ NumericTypes.UInt16 | NumericTypes.Int32 | NumericTypes.UInt32 | NumericTypes.Int64 | NumericTypes.UInt64 | NumericTypes.Single | NumericTypes.Double | NumericTypes.Decimal | NumericTypes.IntPtr | NumericTypes.UIntPtr,
/* SByte */ NumericTypes.Int16 | NumericTypes.Int32 | NumericTypes.Int64 | NumericTypes.Single | NumericTypes.Double | NumericTypes.Decimal | NumericTypes.IntPtr,
/* Byte */ NumericTypes.Int16 | NumericTypes.UInt16 | NumericTypes.Int32 | NumericTypes.UInt32 | NumericTypes.Int64 | NumericTypes.UInt64 | NumericTypes.Single | NumericTypes.Double | NumericTypes.Decimal | NumericTypes.IntPtr | NumericTypes.UIntPtr,
/* Int16 */ NumericTypes.Int32 | NumericTypes.Int64 | NumericTypes.Single | NumericTypes.Double | NumericTypes.Decimal | NumericTypes.IntPtr,
/* UInt16 */ NumericTypes.Int32 | NumericTypes.UInt32 | NumericTypes.Int64 | NumericTypes.UInt64 | NumericTypes.Single | NumericTypes.Double | NumericTypes.Decimal | NumericTypes.IntPtr | NumericTypes.UIntPtr,
/* Int32 */ NumericTypes.Int64 | NumericTypes.Single | NumericTypes.Double | NumericTypes.Decimal | NumericTypes.IntPtr,
/* UInt32 */ NumericTypes.Int64 | NumericTypes.UInt64 | NumericTypes.Single | NumericTypes.Double | NumericTypes.Decimal | NumericTypes.UIntPtr,
/* Int64 */ NumericTypes.Single | NumericTypes.Double | NumericTypes.Decimal,
/* UInt64 */ NumericTypes.Single | NumericTypes.Double | NumericTypes.Decimal,
/* IntPtr */ NumericTypes.Int64 | NumericTypes.Single | NumericTypes.Double | NumericTypes.Decimal,
/* UIntPtr */ NumericTypes.UInt64 | NumericTypes.Single | NumericTypes.Double | NumericTypes.Decimal,
/* Single */ NumericTypes.Double,
/* Double */ NumericTypes.None,
/* Decimal */ NumericTypes.None
};
public static bool IsStatic(this Type type)
{
return type.IsAbstract && type.IsSealed;
}
public static bool IsSpecific(this Type type)
{
return !type.IsGenericParameter && !type.ContainsGenericParameters;
}
public static bool IsFullyPublic(this Type type)
{
return type.IsPublic || (type.IsNestedPublic && type.DeclaringType.IsFullyPublic());
}
public static bool IsCompilerGenerated(this Type type, IHostContext context)
{
return type.HasCustomAttributes<CompilerGeneratedAttribute>(context, false);
}
public static bool IsFlagsEnum(this Type type, IHostContext context)
{
return type.IsEnum && type.HasCustomAttributes<FlagsAttribute>(context, false);
}
public static bool IsImportable(this Type type, IHostContext context)
{
if (!type.IsNested && !type.IsSpecialName && !type.IsCompilerGenerated(context))
{
var locator = type.GetLocator();
return !importDenyList.Contains(locator) && IsValidLocator(locator);
}
return false;
}
public static bool IsAnonymous(this Type type, IHostContext context)
{
if (!type.IsGenericType)
{
return false;
}
if ((type.Attributes & TypeAttributes.VisibilityMask) != TypeAttributes.NotPublic)
{
return false;
}
var name = type.Name;
if (!name.StartsWith("<>", StringComparison.Ordinal) && !name.StartsWith("VB$", StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (!name.Contains("AnonymousType"))
{
return false;
}
if (!type.IsCompilerGenerated(context))
{
return false;
}
return true;
}
public static bool IsIntegral(this Type type)
{
return
(type == typeof(char)) ||
(type == typeof(sbyte)) ||
(type == typeof(byte)) ||
(type == typeof(short)) ||
(type == typeof(ushort)) ||
(type == typeof(int)) ||
(type == typeof(uint)) ||
(type == typeof(long)) ||
(type == typeof(ulong)) ||
(type == typeof(IntPtr)) ||
(type == typeof(UIntPtr));
}
public static bool IsFloatingPoint(this Type type)
{
return
(type == typeof(float)) ||
(type == typeof(double)) ||
(type == typeof(decimal));
}
public static bool IsNumeric(this Type type, out bool isIntegral)
{
return (isIntegral = type.IsIntegral()) || type.IsFloatingPoint();
}
public static bool IsNumeric(this Type type)
{
return type.IsNumeric(out _);
}
public static bool IsNullable(this Type type)
{
return type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(Nullable<>));
}
public static bool IsNullableNumeric(this Type type)
{
return
(type == typeof(char?)) ||
(type == typeof(sbyte?)) ||
(type == typeof(byte?)) ||
(type == typeof(short?)) ||
(type == typeof(ushort?)) ||
(type == typeof(int?)) ||
(type == typeof(uint?)) ||
(type == typeof(long?)) ||
(type == typeof(ulong?)) ||
(type == typeof(IntPtr?)) ||
(type == typeof(UIntPtr?)) ||
(type == typeof(float?)) ||
(type == typeof(double?)) ||
(type == typeof(decimal?));
}
public static bool IsUnknownCOMObject(this Type type)
{
if (!type.IsCOMObject)
{
return false;
}
var found = false;
var interfaces = type.GetInterfaces();
for (var index = 0; index < interfaces.Length; index++)
{
if (interfaces[index].FullName != "System.Runtime.InteropServices.IDynamicInterfaceCastable")
{
found = true;
break;
}
}
return !found;
}
public static bool IsAssignableFromValue(this Type type, IHostContext context, ref object value)
{
return type.IsAssignableFromValueInternal(context, ref value, null, null);
}
public static bool IsAssignableToGenericType(this Type type, Type genericTypeDefinition, out Type[] typeArgs)
{
Debug.Assert(genericTypeDefinition.IsGenericTypeDefinition);
for (var testType = type; testType is not null; testType = testType.BaseType)
{
if (testType.IsGenericType && (testType.GetGenericTypeDefinition() == genericTypeDefinition))
{
typeArgs = testType.GetGenericArguments();
return true;
}
}
var matches = type.GetInterfaces().Where(testType => testType.IsGenericType && (testType.GetGenericTypeDefinition() == genericTypeDefinition)).ToArray();
if (matches.Length == 1)
{
typeArgs = matches[0].GetGenericArguments();
return true;
}
typeArgs = null;
return false;
}
public static bool IsImplicitlyConvertibleFromValue(this Type type, Type sourceType, ref object value)
{
return IsImplicitlyConvertibleFromValueInternal(type, sourceType, type, ref value) || IsImplicitlyConvertibleFromValueInternal(sourceType, sourceType, type, ref value);
}
public static bool IsNumericallyConvertibleFrom(this Type type, Type valueType)
{
return numericConversions[(int)valueType.GetNumericType()].HasAllFlags(GetNumericTypes(type.GetNumericType()));
}
public static bool HasExtensionMethods(this Type type, IHostContext context)
{
return type.HasCustomAttributes<ExtensionAttribute>(context, false);
}
public static bool EqualsOrDeclares(this Type type, Type thatType)
{
for (; thatType is not null; thatType = thatType.DeclaringType)
{
if (thatType == type)
{
return true;
}
}
return false;
}
public static bool IsFamilyOf(this Type type, Type thatType)
{
for (; type is not null; type = type.DeclaringType)
{
if ((type == thatType) || type.IsSubclassOf(thatType))
{
return true;
}
}
return false;
}
public static bool IsFriendOf(this Type type, IHostContext context, Type thatType)
{
return type.Assembly.IsFriendOf(context, thatType.Assembly);
}
public static bool IsCOMVisible(this Type type, IHostContext context)
{
if (!type.IsFullyPublic())
{
return false;
}
var attribute = type.GetOrLoadCustomAttribute<ComVisibleAttribute>(context, false);
if (attribute is not null)
{
return attribute.Value;
}
attribute = type.Assembly.GetOrLoadCustomAttribute<ComVisibleAttribute>(context, false);
if (attribute is not null)
{
return attribute.Value;
}
return true;
}
public static string GetRootName(this Type type)
{
return StripGenericSuffix(type.Name);
}
public static string GetFullRootName(this Type type)
{
return StripGenericSuffix(type.FullName);
}
public static string GetFriendlyName(this Type type)
{
if (type.IsUnknownCOMObject())
{
var clsid = type.GUID;
if (HResult.Succeeded(NativeMethods.ProgIDFromCLSID(ref clsid, out var progID)))
{
return progID;
}
}
return type.GetFriendlyName(GetRootName);
}
public static string GetFullFriendlyName(this Type type)
{
if (type.IsUnknownCOMObject())
{
var clsid = type.GUID;
if (HResult.Succeeded(NativeMethods.ProgIDFromCLSID(ref clsid, out var progID)))
{
return progID;
}
}
return type.GetFriendlyName(GetFullRootName);
}
public static string GetLocator(this Type type)
{
Debug.Assert(!type.IsNested);
return type.GetFullRootName();
}
public static int GetGenericParamCount(this Type type)
{
return type.GetGenericArguments().Count(typeArg => typeArg.IsGenericParameter);
}
public static IEnumerable<EventInfo> GetScriptableEvents(this Type type, IHostContext context, BindingFlags bindFlags)
{
var events = type.GetEvents(bindFlags).AsEnumerable();
if (type.IsInterface)
{
events = events.Concat(type.GetInterfaces().SelectMany(interfaceType => interfaceType.GetScriptableEvents(context, bindFlags)));
}
return events.Where(eventInfo => eventInfo.IsScriptable(context));
}
public static EventInfo GetScriptableEvent(this Type type, IHostContext context, string name, BindingFlags bindFlags)
{
try
{
var eventInfo = type.GetScriptableEventInternal(context, name, bindFlags);
if (eventInfo is not null)
{
return eventInfo;
}
}
catch (AmbiguousMatchException)
{
}
return type.GetScriptableEvents(context, bindFlags).FirstOrDefault(eventInfo => string.Equals(eventInfo.GetScriptName(context), name, bindFlags.GetMemberNameComparison()));
}
public static IEnumerable<FieldInfo> GetScriptableFields(this Type type, IHostContext context, BindingFlags bindFlags)
{
return type.GetFields(bindFlags).Where(field => field.IsScriptable(context));
}
public static FieldInfo GetScriptableField(this Type type, IHostContext context, string name, BindingFlags bindFlags)
{
var candidate = type.GetField(name, bindFlags);
if ((candidate is not null) && candidate.IsScriptable(context) && string.Equals(candidate.GetScriptName(context), name, bindFlags.GetMemberNameComparison()))
{
return candidate;
}
return type.GetScriptableFields(context, bindFlags).FirstOrDefault(field => string.Equals(field.GetScriptName(context), name, bindFlags.GetMemberNameComparison()));
}
public static IEnumerable<MethodInfo> GetScriptableMethods(this Type type, IHostContext context, BindingFlags bindFlags)
{
var methods = type.GetMethods(bindFlags).AsEnumerable();
if (type.IsInterface)
{
methods = methods.Concat(type.GetInterfaces().SelectMany(interfaceType => interfaceType.GetScriptableMethods(context, bindFlags)));
methods = methods.Concat(typeof(object).GetScriptableMethods(context, bindFlags));
}
return methods.Where(method => method.IsScriptable(context));
}
public static IEnumerable<MethodInfo> GetScriptableMethods(this Type type, IHostContext context, string name, BindingFlags bindFlags)
{
return type.GetScriptableMethods(context, bindFlags).Where(method => string.Equals(method.GetScriptName(context), name, bindFlags.GetMemberNameComparison()));
}
public static IEnumerable<PropertyInfo> GetScriptableProperties(this Type type, IHostContext context, BindingFlags bindFlags)
{
var properties = type.GetProperties(bindFlags).AsEnumerable();
if (type.IsInterface)
{
properties = properties.Concat(type.GetInterfaces().SelectMany(interfaceType => interfaceType.GetScriptableProperties(context, bindFlags)));
}
return properties.Where(property => property.IsScriptable(context));
}
public static IEnumerable<PropertyInfo> GetScriptableDefaultProperties(this Type type, IHostContext context, BindingFlags bindFlags)
{
if (type.IsArray)
{
var property = typeof(IList<>).MakeSpecificType(type.GetElementType()).GetProperty("Item");
return (property is not null) ? property.ToEnumerable() : ArrayHelpers.GetEmptyArray<PropertyInfo>();
}
var properties = type.GetProperties(bindFlags).AsEnumerable();
if (type.IsInterface)
{
properties = properties.Concat(type.GetInterfaces().SelectMany(interfaceType => interfaceType.GetScriptableProperties(context, bindFlags)));
}
var defaultMembers = type.GetDefaultMembers();
return properties.Where(property => property.IsScriptable(context) && (defaultMembers.Contains(property) || property.IsDispID(context, SpecialDispIDs.Default)));
}
public static IEnumerable<PropertyInfo> GetScriptableProperties(this Type type, IHostContext context, string name, BindingFlags bindFlags)
{
return type.GetScriptableProperties(context, bindFlags).Where(property => string.Equals(property.GetScriptName(context), name, bindFlags.GetMemberNameComparison()));
}
public static PropertyInfo GetScriptableProperty(this Type type, IHostContext context, string name, BindingFlags bindFlags)
{
var candidates = type.GetProperty(name, bindFlags)?.ToEnumerable() ?? Enumerable.Empty<PropertyInfo>();
if (type.IsInterface)
{
candidates = candidates.Concat(type.GetInterfaces().Select(interfaceType => interfaceType.GetScriptableProperty(context, name, bindFlags)));
}
try
{
// ReSharper disable once RedundantEnumerableCastCall
return candidates.OfType<PropertyInfo>().SingleOrDefault(property => (property.GetIndexParameters().Length < 1) && property.IsScriptable(context) && string.Equals(property.GetScriptName(context), name, bindFlags.GetMemberNameComparison()));
}
catch (InvalidOperationException exception)
{
throw new AmbiguousMatchException($"Multiple matches found for property name '{name}'", exception);
}
}
public static PropertyInfo GetScriptableProperty(this Type type, IHostContext context, string name, BindingFlags bindFlags, object[] args, object[] bindArgs)
{
if (bindArgs.Length < 1)
{
try
{
var property = type.GetScriptableProperty(context, name, bindFlags);
if (property is not null)
{
return property;
}
}
catch (AmbiguousMatchException)
{
}
}
var candidates = type.GetScriptableProperties(context, name, bindFlags).Distinct(PropertySignatureComparer.Instance).ToArray();
return BindToMember(context, candidates, bindFlags, args, bindArgs);
}
public static PropertyInfo GetScriptableDefaultProperty(this Type type, IHostContext context, BindingFlags bindFlags, object[] args, object[] bindArgs)
{
var candidates = type.GetScriptableDefaultProperties(context, bindFlags).Distinct(PropertySignatureComparer.Instance).ToArray();
return BindToMember(context, candidates, bindFlags, args, bindArgs);
}
public static IEnumerable<Type> GetScriptableNestedTypes(this Type type, IHostContext context, BindingFlags bindFlags)
{
return type.GetNestedTypes(bindFlags).Where(nestedType => nestedType.IsScriptable(context));
}
public static Invocability GetInvocability(this Type type, IHostContext context, BindingFlags bindFlags, bool ignoreDynamic)
{
return invocabilityMap.GetOrAdd(Tuple.Create(type, bindFlags, context.AccessContext, context.DefaultAccess, ignoreDynamic), _ => GetInvocabilityInternal(type, context, bindFlags, ignoreDynamic));
}
public static object CreateInstance(this Type type, params object[] args)
{
return type.CreateInstance(BindingFlags.Public, args);
}
public static object CreateInstance(this Type type, BindingFlags flags, params object[] args)
{
return type.InvokeMember(string.Empty, BindingFlags.CreateInstance | BindingFlags.Instance | (flags & ~BindingFlags.Static), null, null, args, CultureInfo.InvariantCulture);
}
public static object CreateInstance(this Type type, IHostContext context, HostTarget target, object[] args, object[] bindArgs)
{
if (type.IsCOMObject)
{
return type.CreateInstance(args);
}
const BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
var signature = new BindSignature(context.AccessContext, flags, target, type.TypeHandle.Value.ToString(), ArrayHelpers.GetEmptyArray<Type>(), bindArgs);
if (context.Engine.TryGetCachedConstructorBindResult(signature, out var boundConstructor))
{
return InvokeHelpers.InvokeConstructor(context, boundConstructor, args);
}
var constructors = type.GetConstructors(flags);
if (type.IsValueType && (args.Length < 1) && !constructors.Any(testConstructor => testConstructor.GetParameters().Length < 1))
{
return type.CreateInstance();
}
var candidates = constructors.Where(testConstructor => testConstructor.IsAccessible(context) && !testConstructor.IsBlockedFromScript(context, context.DefaultAccess)).ToArray();
if (candidates.Length < 1)
{
throw new MissingMethodException(MiscHelpers.FormatInvariant("Type '{0}' has no constructor that matches the specified arguments", type.GetFullFriendlyName()));
}
var constructor = BindToMember(context, candidates, flags, args, bindArgs);
if (constructor is null)
{
throw new MissingMethodException(MiscHelpers.FormatInvariant("Type '{0}' has no constructor that matches the specified arguments", type.GetFullFriendlyName()));
}
context.Engine.CacheConstructorBindResult(signature, constructor);
return InvokeHelpers.InvokeConstructor(context, constructor, args);
}
public static Type MakeSpecificType(this Type template, params Type[] typeArgs)
{
Debug.Assert(template.GetGenericParamCount() <= typeArgs.Length);
return template.ApplyTypeArguments(typeArgs);
}
public static Type ApplyTypeArguments(this Type type, params Type[] typeArgs)
{
if (!type.IsSpecific())
{
Debug.Assert(typeArgs.All(typeArg => typeArg.IsSpecific()));
var finalTypeArgs = (Type[])type.GetGenericArguments().Clone();
for (int finalIndex = 0, index = 0; finalIndex < finalTypeArgs.Length; finalIndex++)
{
if (finalTypeArgs[finalIndex].IsGenericParameter)
{
finalTypeArgs[finalIndex] = typeArgs[index++];
if (index >= typeArgs.Length)
{
break;
}
}
}
return type.GetGenericTypeDefinition().MakeGenericType(finalTypeArgs);
}
return type;
}
public static T BindToMember<T>(IHostContext context, T[] candidates, BindingFlags bindFlags, object[] args, object[] bindArgs) where T : MethodBase
{
T result = null;
if (candidates.Length > 0)
{
var bindCandidates = GetBindCandidates(context, candidates, args, bindArgs.Select(GetBindArgType).ToArray()).ToArray();
result = SelectBindCandidate(bindCandidates);
}
return result;
}
public static PropertyInfo BindToMember(IHostContext context, PropertyInfo[] candidates, BindingFlags bindFlags, object[] args, object[] bindArgs)
{
PropertyInfo result = null;
if (candidates.Length > 0)
{
var bindCandidates = GetBindCandidates(context, candidates, args, bindArgs.Select(GetBindArgType).ToArray()).ToArray();
result = SelectBindCandidate(bindCandidates);
if (result is null)
{
// the default binder fails to bind to some COM properties because of by-ref parameter types
if (candidates.Length == 1)
{
var parameters = candidates[0].GetIndexParameters();
if ((bindArgs.Length == parameters.Length) || ((bindArgs.Length > 0) && (parameters.Length >= bindArgs.Length)))
{
result = candidates[0];
}
}
}
}
return result;
}
public static HostType ImportType(string typeName, string assemblyName, bool useAssemblyName, object[] hostTypeArgs)
{
if (!IsValidLocator(typeName))
{
throw new ArgumentException("Invalid type name", nameof(typeName));
}
if (useAssemblyName && string.IsNullOrWhiteSpace(assemblyName))
{
throw new ArgumentException("Invalid assembly name", nameof(assemblyName));
}
if (!hostTypeArgs.All(arg => arg is HostType))
{
throw new ArgumentException("Invalid generic type argument", nameof(hostTypeArgs));
}
var typeArgs = hostTypeArgs.Cast<HostType>().Select(hostType => hostType.GetTypeArg()).ToArray();
return ImportType(typeName, assemblyName, useAssemblyName, typeArgs);
}
public static HostType ImportType(string typeName, string assemblyName, bool useAssemblyName, Type[] typeArgs)
{
const int maxTypeArgCount = 16;
if ((typeArgs is not null) && (typeArgs.Length > 0))
{
var template = ImportType(typeName, assemblyName, useAssemblyName, typeArgs.Length);
if (template is null)
{
throw new TypeLoadException(MiscHelpers.FormatInvariant("Could not find a matching generic type definition for '{0}'", typeName));
}
return HostType.Wrap(template.MakeSpecificType(typeArgs));
}
var type = ImportType(typeName, assemblyName, useAssemblyName, 0);
// ReSharper disable RedundantEnumerableCastCall
// the OfType<Type>() call is not redundant; it filters out null elements
var counts = Enumerable.Range(1, maxTypeArgCount);
var templates = counts.Select(count => ImportType(typeName, assemblyName, useAssemblyName, count)).OfType<Type>().ToArray();
// ReSharper restore RedundantEnumerableCastCall
if (templates.Length < 1)
{
if (type is null)
{
throw new TypeLoadException(MiscHelpers.FormatInvariant("Could not find a specific type or generic type definition for '{0}'", typeName));
}
return HostType.Wrap(type);
}
if (type is null)
{
return HostType.Wrap(templates);
}
return HostType.Wrap(type.ToEnumerable().Concat(templates).ToArray());
}
private static Type ImportType(string typeName, string assemblyName, bool useAssemblyName, int typeArgCount)
{
var assemblyQualifiedName = GetFullTypeName(typeName, assemblyName, useAssemblyName, typeArgCount);
Type type = null;
try
{
type = Type.GetType(assemblyQualifiedName);
}
catch (ArgumentException)
{
}
catch (TypeLoadException)
{
}
catch (FileLoadException)
{
}
return ((type is not null) && useAssemblyName && (type.AssemblyQualifiedName != assemblyQualifiedName)) ? null : type;
}
private static string GetFriendlyName(this Type type, Func<Type, string> getBaseName)
{
Debug.Assert(type.IsSpecific());
if (type.IsArray)
{
var commas = new string(Enumerable.Repeat(',', type.GetArrayRank() - 1).ToArray());
return MiscHelpers.FormatInvariant("{0}[{1}]", type.GetElementType().GetFriendlyName(getBaseName), commas);
}
var typeArgs = type.GetGenericArguments();
var parentPrefix = string.Empty;
if (type.IsNested)
{
var parentType = type.DeclaringType.MakeSpecificType(typeArgs);
parentPrefix = parentType.GetFriendlyName(getBaseName) + ".";
typeArgs = typeArgs.Skip(parentType.GetGenericArguments().Length).ToArray();
getBaseName = GetRootName;
}
if (typeArgs.Length < 1)
{
return MiscHelpers.FormatInvariant("{0}{1}", parentPrefix, getBaseName(type));
}
var name = getBaseName(type.GetGenericTypeDefinition());
var paramList = string.Join(",", typeArgs.Select(typeArg => typeArg.GetFriendlyName(getBaseName)));
return MiscHelpers.FormatInvariant("{0}{1}<{2}>", parentPrefix, name, paramList);
}
private static EventInfo GetScriptableEventInternal(this Type type, IHostContext context, string name, BindingFlags bindFlags)
{
var candidates = type.GetEvent(name, bindFlags)?.ToEnumerable() ?? Enumerable.Empty<EventInfo>();
if (type.IsInterface)
{
candidates = candidates.Concat(type.GetInterfaces().Select(interfaceType => interfaceType.GetScriptableEventInternal(context, name, bindFlags)));
}
try
{
// ReSharper disable once RedundantEnumerableCastCall
return candidates.OfType<EventInfo>().SingleOrDefault(eventInfo => eventInfo.IsScriptable(context) && string.Equals(eventInfo.GetScriptName(context), name, bindFlags.GetMemberNameComparison()));
}
catch (InvalidOperationException exception)
{
throw new AmbiguousMatchException($"Multiple matches found for event name '{name}'", exception);
}
}
private static Invocability GetInvocabilityInternal(Type type, IHostContext context, BindingFlags bindFlags, bool ignoreDynamic)
{
if (typeof(Delegate).IsAssignableFrom(type))
{
return Invocability.Delegate;
}
if (!ignoreDynamic && typeof(IDynamicMetaObjectProvider).IsAssignableFrom(type))
{
return Invocability.Dynamic;
}
if (type.GetScriptableDefaultProperties(context, bindFlags).Any())
{
return Invocability.DefaultProperty;
}
return Invocability.None;
}
private static bool IsValidLocator(string name)
{
return !string.IsNullOrWhiteSpace(name) && name.All(IsValidLocatorChar);
}
private static bool IsValidLocatorChar(char ch)
{
return char.IsLetterOrDigit(ch) || (ch == '_') || (ch == '.');
}
private static string StripGenericSuffix(string name)
{
Debug.Assert(!string.IsNullOrWhiteSpace(name));
var index = name.LastIndexOf('`');
return (index >= 0) ? name.Substring(0, index) : name;
}
private static bool IsBindableFromArg(this Type type, IHostContext context, object value, Type valueType, out BindArgCost cost)
{
cost = new BindArgCost();
return type.IsAssignableFromValueInternal(context, ref value, valueType, cost);
}
private static bool IsAssignableFromValueInternal(this Type type, IHostContext context, ref object value, Type valueType, BindArgCost cost)
{
var typeIsByRef = type.IsByRef;
if (typeIsByRef)
{
type = type.GetElementType();
}
var valueIsByRef = (valueType is not null) && valueType.IsByRef;
if (valueIsByRef)
{
valueType = valueType.GetElementType();
}
if ((cost is not null) && (typeIsByRef != valueIsByRef))
{
cost.Flags |= BindArgFlags.ByRefMismatch;
}
if ((value is null) && (valueType is null))
{
if (type.IsNullable())
{
if (cost is not null)
{
cost.NumericType = Nullable.GetUnderlyingType(type).GetNumericType();
}
return true;
}
return !type.IsValueType;
}
if (valueType is null)
{
valueType = value.GetType();
}
if (valueType == type)
{
return true;
}
if (type.IsAssignableFrom(valueType))
{
if (cost is not null)
{
if (type.IsNullable())
{
cost.Flags |= BindArgFlags.NullableTransition;
cost.NumericType = Nullable.GetUnderlyingType(type).GetNumericType();
}
else if (TypeNode.TryGetUpcastCount(valueType, type, out var count))
{
cost.UpcastCount = count;
}
}
return true;
}
if (type.IsImplicitlyConvertibleFromValue(valueType, ref value))
{
if (cost is not null)
{
cost.Flags |= BindArgFlags.ImplicitConversion;
}
return true;
}
if (value is null)
{
return false;
}
if (type.IsNullable())
{
var underlyingType = Nullable.GetUnderlyingType(type);
if (underlyingType.IsAssignableFromValueInternal(context, ref value, valueType, cost))
{
if (cost is not null)
{
cost.Flags |= BindArgFlags.NullableTransition;
cost.NumericType = underlyingType.GetNumericType();
}
return true;
}
return false;
}
if (!type.IsValueType)
{
if (type.IsInterface && type.IsImport && valueType.IsCOMObject)
{
var result = false;
var pUnknown = Marshal.GetIUnknownForObject(value);
var iid = type.GUID;
if (iid != Guid.Empty)
{
if (HResult.Succeeded(Marshal.QueryInterface(pUnknown, ref iid, out var pInterface)))
{
Marshal.Release(pInterface);
result = true;
}
}
Marshal.Release(pUnknown);
return result;
}
return false;
}
if (!valueType.IsValueType)
{
return false;
}
if (type.IsEnum)
{
var isValid = Enum.GetUnderlyingType(type).IsAssignableFromValueInternal(context, ref value, valueType, cost);
if (!isValid)
{
return false;
}
if (context.Engine.AcceptEnumAsUnderlyingType)
{
if (cost is not null)
{
cost.Flags |= BindArgFlags.EnumConversion;
}
return true;
}
return value.IsZero();
}
if (valueType.IsEnum)
{
return false;
}
if (type.IsNumeric(out var typeIsIntegral))
{
if (typeIsIntegral)
{
if (!valueType.IsIntegral() && !value.IsWholeNumber())
{
return false;
}
}
else
{
if (!valueType.IsNumeric(out var valueTypeIsIntegral))
{
return false;
}
// special case for method binding only
if ((cost is not null) && !valueTypeIsIntegral && !type.IsNumericallyConvertibleFrom(valueType))
{
return false;
}
}
var tempValue = value;
if (MiscHelpers.Try(out var tempResult, static ctx => Convert.ChangeType(ctx.tempValue, ctx.type), (tempValue, type)))
{
if (cost is not null)
{
cost.Flags |= BindArgFlags.NumericConversion;
cost.NumericType = type.GetNumericType();
}
value = tempResult;
return true;
}
}
return false;
}
private static bool IsImplicitlyConvertibleFromValueInternal(Type definingType, Type sourceType, Type targetType, ref object value)
{
foreach (var converter in definingType.GetMethods(BindingFlags.Public | BindingFlags.Static).Where(method => method.Name == "op_Implicit"))
{
var parameters = converter.GetParameters();
if ((parameters.Length == 1) && parameters[0].ParameterType.IsAssignableFrom(sourceType) && targetType.IsAssignableFrom(converter.ReturnType))
{
var args = new[] { value };
if (MiscHelpers.Try(out var result, static ctx => ctx.converter.Invoke(null, ctx.args), (converter, args)))
{
value = result;
return true;