-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathReflectionExtensions.cs
327 lines (283 loc) · 14.4 KB
/
ReflectionExtensions.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.Reflection;
using System.Collections.Generic;
#if !BUILDING_SOURCE_GENERATOR
using System.Diagnostics.CodeAnalysis;
#endif
namespace System.Text.Json.Reflection
{
internal static partial class ReflectionExtensions
{
// Immutable collection types.
private const string ImmutableArrayGenericTypeName = "System.Collections.Immutable.ImmutableArray`1";
private const string ImmutableListGenericTypeName = "System.Collections.Immutable.ImmutableList`1";
private const string ImmutableListGenericInterfaceTypeName = "System.Collections.Immutable.IImmutableList`1";
private const string ImmutableStackGenericTypeName = "System.Collections.Immutable.ImmutableStack`1";
private const string ImmutableStackGenericInterfaceTypeName = "System.Collections.Immutable.IImmutableStack`1";
private const string ImmutableQueueGenericTypeName = "System.Collections.Immutable.ImmutableQueue`1";
private const string ImmutableQueueGenericInterfaceTypeName = "System.Collections.Immutable.IImmutableQueue`1";
private const string ImmutableSortedSetGenericTypeName = "System.Collections.Immutable.ImmutableSortedSet`1";
private const string ImmutableHashSetGenericTypeName = "System.Collections.Immutable.ImmutableHashSet`1";
private const string ImmutableSetGenericInterfaceTypeName = "System.Collections.Immutable.IImmutableSet`1";
private const string ImmutableDictionaryGenericTypeName = "System.Collections.Immutable.ImmutableDictionary`2";
private const string ImmutableDictionaryGenericInterfaceTypeName = "System.Collections.Immutable.IImmutableDictionary`2";
private const string ImmutableSortedDictionaryGenericTypeName = "System.Collections.Immutable.ImmutableSortedDictionary`2";
// Immutable collection builder types.
private const string ImmutableArrayTypeName = "System.Collections.Immutable.ImmutableArray";
private const string ImmutableListTypeName = "System.Collections.Immutable.ImmutableList";
private const string ImmutableStackTypeName = "System.Collections.Immutable.ImmutableStack";
private const string ImmutableQueueTypeName = "System.Collections.Immutable.ImmutableQueue";
private const string ImmutableSortedSetTypeName = "System.Collections.Immutable.ImmutableSortedSet";
private const string ImmutableHashSetTypeName = "System.Collections.Immutable.ImmutableHashSet";
private const string ImmutableDictionaryTypeName = "System.Collections.Immutable.ImmutableDictionary";
private const string ImmutableSortedDictionaryTypeName = "System.Collections.Immutable.ImmutableSortedDictionary";
public const string CreateRangeMethodName = "CreateRange";
public static Type? GetCompatibleGenericBaseClass(
this Type type,
Type baseType,
Type? objectType = null,
bool sourceGenType = false)
{
Debug.Assert(baseType.IsGenericType);
Debug.Assert(!baseType.IsInterface);
Debug.Assert(baseType == baseType.GetGenericTypeDefinition());
// Work around not being able to use typeof(object) directly during compile-time src gen type analysis.
objectType ??= typeof(object);
Type? baseTypeToCheck = type;
while (baseTypeToCheck != null && baseTypeToCheck != typeof(object))
{
if (baseTypeToCheck.IsGenericType)
{
Type genericTypeToCheck = baseTypeToCheck.GetGenericTypeDefinition();
if (genericTypeToCheck == baseType ||
(sourceGenType && (OpenGenericTypesHaveSamePrefix(baseType, genericTypeToCheck))))
{
return baseTypeToCheck;
}
}
baseTypeToCheck = baseTypeToCheck.BaseType;
}
return null;
}
#if !BUILDING_SOURCE_GENERATOR
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern",
Justification = "The 'interfaceType' must exist and so trimmer kept it. In which case " +
"It also kept it on any type which implements it. The below call to GetInterfaces " +
"may return fewer results when trimmed but it will return the 'interfaceType' " +
"if the type implemented it, even after trimming.")]
#endif
public static Type? GetCompatibleGenericInterface(this Type type, Type interfaceType)
{
Debug.Assert(interfaceType.IsGenericType);
Debug.Assert(interfaceType.IsInterface);
Debug.Assert(interfaceType == interfaceType.GetGenericTypeDefinition());
Type interfaceToCheck = type;
if (interfaceToCheck.IsGenericType)
{
interfaceToCheck = interfaceToCheck.GetGenericTypeDefinition();
}
if (interfaceToCheck == interfaceType)
{
return type;
}
foreach (Type typeToCheck in type.GetInterfaces())
{
if (typeToCheck.IsGenericType)
{
Type genericInterfaceToCheck = typeToCheck.GetGenericTypeDefinition();
if (genericInterfaceToCheck == interfaceType)
{
return typeToCheck;
}
}
}
return null;
}
public static bool IsImmutableDictionaryType(this Type type, bool sourceGenType = false)
{
if (!type.IsGenericType || !type.Assembly.FullName!.StartsWith("System.Collections.Immutable", StringComparison.Ordinal))
{
return false;
}
switch (GetBaseNameFromGenericType(type, sourceGenType))
{
case ImmutableDictionaryGenericTypeName:
case ImmutableDictionaryGenericInterfaceTypeName:
case ImmutableSortedDictionaryGenericTypeName:
return true;
default:
return false;
}
}
public static bool IsImmutableEnumerableType(this Type type, bool sourceGenType = false)
{
if (!type.IsGenericType || !type.Assembly.FullName!.StartsWith("System.Collections.Immutable", StringComparison.Ordinal))
{
return false;
}
switch (GetBaseNameFromGenericType(type, sourceGenType))
{
case ImmutableArrayGenericTypeName:
case ImmutableListGenericTypeName:
case ImmutableListGenericInterfaceTypeName:
case ImmutableStackGenericTypeName:
case ImmutableStackGenericInterfaceTypeName:
case ImmutableQueueGenericTypeName:
case ImmutableQueueGenericInterfaceTypeName:
case ImmutableSortedSetGenericTypeName:
case ImmutableHashSetGenericTypeName:
case ImmutableSetGenericInterfaceTypeName:
return true;
default:
return false;
}
}
public static string? GetImmutableDictionaryConstructingTypeName(this Type type, bool sourceGenType = false)
{
Debug.Assert(type.IsImmutableDictionaryType(sourceGenType));
// Use the generic type definition of the immutable collection to determine
// an appropriate constructing type, i.e. a type that we can invoke the
// `CreateRange<T>` method on, which returns the desired immutable collection.
switch (GetBaseNameFromGenericType(type, sourceGenType))
{
case ImmutableDictionaryGenericTypeName:
case ImmutableDictionaryGenericInterfaceTypeName:
return ImmutableDictionaryTypeName;
case ImmutableSortedDictionaryGenericTypeName:
return ImmutableSortedDictionaryTypeName;
default:
// We verified that the type is an immutable collection, so the
// generic definition is one of the above.
return null;
}
}
public static string? GetImmutableEnumerableConstructingTypeName(this Type type, bool sourceGenType = false)
{
Debug.Assert(type.IsImmutableEnumerableType(sourceGenType));
// Use the generic type definition of the immutable collection to determine
// an appropriate constructing type, i.e. a type that we can invoke the
// `CreateRange<T>` method on, which returns the desired immutable collection.
switch (GetBaseNameFromGenericType(type, sourceGenType))
{
case ImmutableArrayGenericTypeName:
return ImmutableArrayTypeName;
case ImmutableListGenericTypeName:
case ImmutableListGenericInterfaceTypeName:
return ImmutableListTypeName;
case ImmutableStackGenericTypeName:
case ImmutableStackGenericInterfaceTypeName:
return ImmutableStackTypeName;
case ImmutableQueueGenericTypeName:
case ImmutableQueueGenericInterfaceTypeName:
return ImmutableQueueTypeName;
case ImmutableSortedSetGenericTypeName:
return ImmutableSortedSetTypeName;
case ImmutableHashSetGenericTypeName:
case ImmutableSetGenericInterfaceTypeName:
return ImmutableHashSetTypeName;
default:
// We verified that the type is an immutable collection, so the
// generic definition is one of the above.
return null;
}
}
private static bool OpenGenericTypesHaveSamePrefix(Type t1, Type t2)
=> t1.FullName == GetBaseNameFromGenericTypeDef(t2);
private static string GetBaseNameFromGenericType(Type genericType, bool sourceGenType)
{
Type genericTypeDef = genericType.GetGenericTypeDefinition();
return sourceGenType ? GetBaseNameFromGenericTypeDef(genericTypeDef) : genericTypeDef.FullName!;
}
private static string GetBaseNameFromGenericTypeDef(Type genericTypeDef)
{
Debug.Assert(genericTypeDef.IsGenericType);
string fullName = genericTypeDef.FullName!;
int length = fullName.IndexOf("`") + 2;
return fullName.Substring(0, length);
}
public static bool IsVirtual(this PropertyInfo? propertyInfo)
{
Debug.Assert(propertyInfo != null);
return propertyInfo != null && (propertyInfo.GetMethod?.IsVirtual == true || propertyInfo.SetMethod?.IsVirtual == true);
}
public static bool IsKeyValuePair(this Type type, Type? keyValuePairType = null)
{
if (!type.IsGenericType)
{
return false;
}
// Work around not being able to use typeof(KeyValuePair<,>) directly during compile-time src gen type analysis.
keyValuePairType ??= typeof(KeyValuePair<,>);
Type generic = type.GetGenericTypeDefinition();
return generic == keyValuePairType;
}
public static bool TryGetDeserializationConstructor(
#if !BUILDING_SOURCE_GENERATOR
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)]
#endif
this Type type,
bool useDefaultCtorInAnnotatedStructs,
out ConstructorInfo? deserializationCtor)
{
ConstructorInfo? ctorWithAttribute = null;
ConstructorInfo? publicParameterlessCtor = null;
ConstructorInfo? lonePublicCtor = null;
ConstructorInfo[] constructors = type.GetConstructors(BindingFlags.Public | BindingFlags.Instance);
if (constructors.Length == 1)
{
lonePublicCtor = constructors[0];
}
foreach (ConstructorInfo constructor in constructors)
{
if (HasJsonConstructorAttribute(constructor))
{
if (ctorWithAttribute != null)
{
deserializationCtor = null;
return false;
}
ctorWithAttribute = constructor;
}
else if (constructor.GetParameters().Length == 0)
{
publicParameterlessCtor = constructor;
}
}
// For correctness, throw if multiple ctors have [JsonConstructor], even if one or more are non-public.
ConstructorInfo? dummyCtorWithAttribute = ctorWithAttribute;
constructors = type.GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance);
foreach (ConstructorInfo constructor in constructors)
{
if (HasJsonConstructorAttribute(constructor))
{
if (dummyCtorWithAttribute != null)
{
deserializationCtor = null;
return false;
}
dummyCtorWithAttribute = constructor;
}
}
// Structs will use default constructor if attribute isn't used.
if (useDefaultCtorInAnnotatedStructs && type.IsValueType && ctorWithAttribute == null)
{
deserializationCtor = null;
return true;
}
deserializationCtor = ctorWithAttribute ?? publicParameterlessCtor ?? lonePublicCtor;
return true;
}
public static object? GetDefaultValue(this ParameterInfo parameterInfo)
{
object? defaultValue = parameterInfo.DefaultValue;
// DBNull.Value is sometimes used as the default value (returned by reflection) of nullable params in place of null.
if (defaultValue == DBNull.Value && parameterInfo.ParameterType != typeof(DBNull))
{
return null;
}
return defaultValue;
}
}
}