forked from dotnet/efcore
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSharedTypeExtensions.cs
More file actions
605 lines (513 loc) · 20.5 KB
/
Copy pathSharedTypeExtensions.cs
File metadata and controls
605 lines (513 loc) · 20.5 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
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using JetBrains.Annotations;
#nullable enable
// ReSharper disable once CheckNamespace
namespace System
{
[DebuggerStepThrough]
internal static class SharedTypeExtensions
{
private static readonly Dictionary<Type, string> _builtInTypeNames = new Dictionary<Type, string>
{
{ typeof(bool), "bool" },
{ typeof(byte), "byte" },
{ typeof(char), "char" },
{ typeof(decimal), "decimal" },
{ typeof(double), "double" },
{ typeof(float), "float" },
{ typeof(int), "int" },
{ typeof(long), "long" },
{ typeof(object), "object" },
{ typeof(sbyte), "sbyte" },
{ typeof(short), "short" },
{ typeof(string), "string" },
{ typeof(uint), "uint" },
{ typeof(ulong), "ulong" },
{ typeof(ushort), "ushort" },
{ typeof(void), "void" }
};
public static Type UnwrapNullableType(this Type type)
=> Nullable.GetUnderlyingType(type) ?? type;
public static bool IsNullableValueType(this Type type)
=> type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
public static bool IsNullableType(this Type type)
=> !type.IsValueType || type.IsNullableValueType();
public static bool IsValidEntityType(this Type type)
=> type.IsClass;
public static bool IsPropertyBagType(this Type type)
{
if (type.IsGenericTypeDefinition)
{
return false;
}
var types = GetGenericTypeImplementations(type, typeof(IDictionary<,>));
return types.Any(
t => t.GetGenericArguments()[0] == typeof(string)
&& t.GetGenericArguments()[1] == typeof(object));
}
public static Type MakeNullable(this Type type, bool nullable = true)
=> type.IsNullableType() == nullable
? type
: nullable
? typeof(Nullable<>).MakeGenericType(type)
: type.UnwrapNullableType();
public static bool IsNumeric(this Type type)
{
type = type.UnwrapNullableType();
return type.IsInteger()
|| type == typeof(decimal)
|| type == typeof(float)
|| type == typeof(double);
}
public static bool IsInteger(this Type type)
{
type = type.UnwrapNullableType();
return type == typeof(int)
|| type == typeof(long)
|| type == typeof(short)
|| type == typeof(byte)
|| type == typeof(uint)
|| type == typeof(ulong)
|| type == typeof(ushort)
|| type == typeof(sbyte)
|| type == typeof(char);
}
public static bool IsSignedInteger(this Type type)
=> type == typeof(int)
|| type == typeof(long)
|| type == typeof(short)
|| type == typeof(sbyte);
public static bool IsAnonymousType(this Type type)
=> type.Name.StartsWith("<>", StringComparison.Ordinal)
&& type.GetCustomAttributes(typeof(CompilerGeneratedAttribute), inherit: false).Length > 0
&& type.Name.Contains("AnonymousType");
public static bool IsTupleType(this Type type)
{
if (type == typeof(Tuple))
{
return true;
}
if (type.IsGenericType)
{
var genericDefinition = type.GetGenericTypeDefinition();
if (genericDefinition == typeof(Tuple<>)
|| genericDefinition == typeof(Tuple<,>)
|| genericDefinition == typeof(Tuple<,,>)
|| genericDefinition == typeof(Tuple<,,,>)
|| genericDefinition == typeof(Tuple<,,,,>)
|| genericDefinition == typeof(Tuple<,,,,,>)
|| genericDefinition == typeof(Tuple<,,,,,,>)
|| genericDefinition == typeof(Tuple<,,,,,,,>)
|| genericDefinition == typeof(Tuple<,,,,,,,>))
{
return true;
}
}
return false;
}
public static PropertyInfo? GetAnyProperty(this Type type, string name)
{
var props = type.GetRuntimeProperties().Where(p => p.Name == name).ToList();
if (props.Count > 1)
{
throw new AmbiguousMatchException();
}
return props.SingleOrDefault();
}
public static MethodInfo GetRequiredMethod(this Type type, string name, params Type[] parameters)
{
var method = type.GetTypeInfo().GetMethod(name, parameters);
if (method == null
&& parameters.Length == 0)
{
method = type.GetMethod(name);
}
if (method == null)
{
throw new InvalidOperationException();
}
return method;
}
public static PropertyInfo GetRequiredProperty(this Type type, string name)
{
var property = type.GetTypeInfo().GetProperty(name);
if (property == null)
{
throw new InvalidOperationException();
}
return property;
}
public static FieldInfo GetRequiredDeclaredField(this Type type, string name)
{
var field = type.GetTypeInfo().GetDeclaredField(name);
if (field == null)
{
throw new InvalidOperationException();
}
return field;
}
public static MethodInfo GetRequiredDeclaredMethod(this Type type, string name)
{
var method = type.GetTypeInfo().GetDeclaredMethod(name);
if (method == null)
{
throw new InvalidOperationException();
}
return method;
}
public static PropertyInfo GetRequiredDeclaredProperty(this Type type, string name)
{
var property = type.GetTypeInfo().GetDeclaredProperty(name);
if (property == null)
{
throw new InvalidOperationException();
}
return property;
}
public static MethodInfo GetRequiredRuntimeMethod(this Type type, string name, params Type[] parameters)
{
var method = type.GetTypeInfo().GetRuntimeMethod(name, parameters);
if (method == null)
{
throw new InvalidOperationException();
}
return method;
}
public static PropertyInfo GetRequiredRuntimeProperty(this Type type, string name)
{
var property = type.GetTypeInfo().GetRuntimeProperty(name);
if (property == null)
{
throw new InvalidOperationException();
}
return property;
}
public static bool IsInstantiable(this Type type)
=> !type.IsAbstract
&& !type.IsInterface
&& (!type.IsGenericType || !type.IsGenericTypeDefinition);
public static Type UnwrapEnumType(this Type type)
{
var isNullable = type.IsNullableType();
var underlyingNonNullableType = isNullable ? type.UnwrapNullableType() : type;
if (!underlyingNonNullableType.IsEnum)
{
return type;
}
var underlyingEnumType = Enum.GetUnderlyingType(underlyingNonNullableType);
return isNullable ? MakeNullable(underlyingEnumType) : underlyingEnumType;
}
public static Type GetSequenceType(this Type type)
{
var sequenceType = TryGetSequenceType(type);
if (sequenceType == null)
{
// TODO: Add exception message
throw new ArgumentException();
}
return sequenceType;
}
#nullable enable
public static Type? TryGetSequenceType(this Type type)
=> type.TryGetElementType(typeof(IEnumerable<>))
?? type.TryGetElementType(typeof(IAsyncEnumerable<>));
public static Type? TryGetElementType(this Type type, Type interfaceOrBaseType)
{
if (type.IsGenericTypeDefinition)
{
return null;
}
var types = GetGenericTypeImplementations(type, interfaceOrBaseType);
Type? singleImplementation = null;
foreach (var implementation in types)
{
if (singleImplementation == null)
{
singleImplementation = implementation;
}
else
{
singleImplementation = null;
break;
}
}
return singleImplementation?.GenericTypeArguments.FirstOrDefault();
}
#nullable disable
public static bool IsCompatibleWith(this Type propertyType, Type fieldType)
{
if (propertyType.IsAssignableFrom(fieldType)
|| fieldType.IsAssignableFrom(propertyType))
{
return true;
}
var propertyElementType = propertyType.TryGetSequenceType();
var fieldElementType = fieldType.TryGetSequenceType();
return propertyElementType != null
&& fieldElementType != null
&& IsCompatibleWith(propertyElementType, fieldElementType);
}
public static IEnumerable<Type> GetGenericTypeImplementations(this Type type, Type interfaceOrBaseType)
{
var typeInfo = type.GetTypeInfo();
if (!typeInfo.IsGenericTypeDefinition)
{
var baseTypes = interfaceOrBaseType.GetTypeInfo().IsInterface
? typeInfo.ImplementedInterfaces
: type.GetBaseTypes();
foreach (var baseType in baseTypes)
{
if (baseType.IsGenericType
&& baseType.GetGenericTypeDefinition() == interfaceOrBaseType)
{
yield return baseType;
}
}
if (type.IsGenericType
&& type.GetGenericTypeDefinition() == interfaceOrBaseType)
{
yield return type;
}
}
}
public static IEnumerable<Type> GetBaseTypes(this Type type)
{
type = type.BaseType;
while (type != null)
{
yield return type;
type = type.BaseType;
}
}
public static IEnumerable<Type> GetTypesInHierarchy(this Type type)
{
while (type != null)
{
yield return type;
type = type.BaseType;
}
}
public static ConstructorInfo GetDeclaredConstructor(this Type type, Type[] types)
{
types ??= Array.Empty<Type>();
return type.GetTypeInfo().DeclaredConstructors
.SingleOrDefault(
c => !c.IsStatic
&& c.GetParameters().Select(p => p.ParameterType).SequenceEqual(types));
}
public static IEnumerable<PropertyInfo> GetPropertiesInHierarchy(this Type type, string name)
{
do
{
var typeInfo = type.GetTypeInfo();
foreach (var propertyInfo in typeInfo.DeclaredProperties)
{
if (propertyInfo.Name.Equals(name, StringComparison.Ordinal)
&& !(propertyInfo.GetMethod ?? propertyInfo.SetMethod).IsStatic)
{
yield return propertyInfo;
}
}
type = typeInfo.BaseType;
}
while (type != null);
}
// Looking up the members through the whole hierarchy allows to find inherited private members.
public static IEnumerable<MemberInfo> GetMembersInHierarchy(this Type type)
{
do
{
// Do the whole hierarchy for properties first since looking for fields is slower.
foreach (var propertyInfo in type.GetRuntimeProperties().Where(pi => !(pi.GetMethod ?? pi.SetMethod).IsStatic))
{
yield return propertyInfo;
}
foreach (var fieldInfo in type.GetRuntimeFields().Where(f => !f.IsStatic))
{
yield return fieldInfo;
}
type = type.BaseType;
}
while (type != null);
}
public static IEnumerable<MemberInfo> GetMembersInHierarchy(this Type type, string name)
=> type.GetMembersInHierarchy().Where(m => m.Name == name);
private static readonly Dictionary<Type, object> _commonTypeDictionary = new Dictionary<Type, object>
{
#pragma warning disable IDE0034 // Simplify 'default' expression - default causes default(object)
{ typeof(int), default(int) },
{ typeof(Guid), default(Guid) },
{ typeof(DateTime), default(DateTime) },
{ typeof(DateTimeOffset), default(DateTimeOffset) },
{ typeof(long), default(long) },
{ typeof(bool), default(bool) },
{ typeof(double), default(double) },
{ typeof(short), default(short) },
{ typeof(float), default(float) },
{ typeof(byte), default(byte) },
{ typeof(char), default(char) },
{ typeof(uint), default(uint) },
{ typeof(ushort), default(ushort) },
{ typeof(ulong), default(ulong) },
{ typeof(sbyte), default(sbyte) }
#pragma warning restore IDE0034 // Simplify 'default' expression
};
public static object GetDefaultValue(this Type type)
{
if (!type.IsValueType)
{
return null;
}
// A bit of perf code to avoid calling Activator.CreateInstance for common types and
// to avoid boxing on every call. This is about 50% faster than just calling CreateInstance
// for all value types.
return _commonTypeDictionary.TryGetValue(type, out var value)
? value
: Activator.CreateInstance(type);
}
public static IEnumerable<TypeInfo> GetConstructibleTypes(this Assembly assembly)
=> assembly.GetLoadableDefinedTypes().Where(
t => !t.IsAbstract
&& !t.IsGenericTypeDefinition);
public static IEnumerable<TypeInfo> GetLoadableDefinedTypes(this Assembly assembly)
{
try
{
return assembly.DefinedTypes;
}
catch (ReflectionTypeLoadException ex)
{
return ex.Types.Where(t => t != null).Select(IntrospectionExtensions.GetTypeInfo);
}
}
public static bool IsQueryableType(this Type type)
{
if (type.IsGenericType
&& type.GetGenericTypeDefinition() == typeof(IQueryable<>))
{
return true;
}
return type.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IQueryable<>));
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public static string DisplayName([NotNull] this Type type, bool fullName = true)
{
var stringBuilder = new StringBuilder();
ProcessType(stringBuilder, type, fullName);
return stringBuilder.ToString();
}
private static void ProcessType(StringBuilder builder, Type type, bool fullName)
{
if (type.IsGenericType)
{
var genericArguments = type.GetGenericArguments();
ProcessGenericType(builder, type, genericArguments, genericArguments.Length, fullName);
}
else if (type.IsArray)
{
ProcessArrayType(builder, type, fullName);
}
else if (_builtInTypeNames.TryGetValue(type, out var builtInName))
{
builder.Append(builtInName);
}
else if (!type.IsGenericParameter)
{
builder.Append(fullName ? type.FullName : type.Name);
}
}
private static void ProcessArrayType(StringBuilder builder, Type type, bool fullName)
{
var innerType = type;
while (innerType.IsArray)
{
innerType = innerType.GetElementType();
}
ProcessType(builder, innerType, fullName);
while (type.IsArray)
{
builder.Append('[');
builder.Append(',', type.GetArrayRank() - 1);
builder.Append(']');
type = type.GetElementType();
}
}
private static void ProcessGenericType(StringBuilder builder, Type type, Type[] genericArguments, int length, bool fullName)
{
var offset = type.IsNested ? type.DeclaringType.GetGenericArguments().Length : 0;
if (fullName)
{
if (type.IsNested)
{
ProcessGenericType(builder, type.DeclaringType, genericArguments, offset, fullName);
builder.Append('+');
}
else
{
builder.Append(type.Namespace);
builder.Append('.');
}
}
var genericPartIndex = type.Name.IndexOf('`');
if (genericPartIndex <= 0)
{
builder.Append(type.Name);
return;
}
builder.Append(type.Name, 0, genericPartIndex);
builder.Append('<');
for (var i = offset; i < length; i++)
{
ProcessType(builder, genericArguments[i], fullName);
if (i + 1 == length)
{
continue;
}
builder.Append(',');
if (!genericArguments[i + 1].IsGenericParameter)
{
builder.Append(' ');
}
}
builder.Append('>');
}
public static IEnumerable<string> GetNamespaces([NotNull] this Type type)
{
if (_builtInTypeNames.ContainsKey(type))
{
yield break;
}
yield return type.Namespace;
if (type.IsGenericType)
{
foreach (var typeArgument in type.GenericTypeArguments)
{
foreach (var ns in typeArgument.GetNamespaces())
{
yield return ns;
}
}
}
}
public static ConstantExpression GetDefaultValueConstant(this Type type)
=> (ConstantExpression)_generateDefaultValueConstantMethod
.MakeGenericMethod(type).Invoke(null, Array.Empty<object>());
private static readonly MethodInfo _generateDefaultValueConstantMethod =
typeof(SharedTypeExtensions).GetTypeInfo().GetDeclaredMethod(nameof(GenerateDefaultValueConstant));
private static ConstantExpression GenerateDefaultValueConstant<TDefault>()
=> Expression.Constant(default(TDefault), typeof(TDefault));
}
}