forked from microsoft/CsWinRT
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTypeNameSupport.cs
More file actions
502 lines (456 loc) · 20.1 KB
/
TypeNameSupport.cs
File metadata and controls
502 lines (456 loc) · 20.1 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
namespace WinRT
{
[Flags]
internal enum TypeNameGenerationFlags
{
None = 0,
/// <summary>
/// Generate the name of the type as if it was boxed in an object.
/// </summary>
GenerateBoxedName = 0x1,
/// <summary>
/// Don't output a type name of a custom .NET type. Generate a compatible WinRT type name if needed.
/// </summary>
NoCustomTypeName = 0x2
}
internal static class TypeNameSupport
{
private static readonly List<Assembly> projectionAssemblies = new List<Assembly>();
private static readonly List<IDictionary<string, string>> projectionTypeNameToBaseTypeNameMappings = new List<IDictionary<string, string>>();
private static readonly ConcurrentDictionary<string, Type> typeNameCache = new ConcurrentDictionary<string, Type>(StringComparer.Ordinal) { ["TrackerCollection<T>"] = null };
private static readonly ConcurrentDictionary<string, Type> baseRcwTypeCache = new ConcurrentDictionary<string, Type>(StringComparer.Ordinal) { ["TrackerCollection<T>"] = null };
public static void RegisterProjectionAssembly(Assembly assembly)
{
projectionAssemblies.Add(assembly);
}
public static void RegisterProjectionTypeBaseTypeMapping(IDictionary<string, string> typeNameToBaseTypeNameMapping)
{
projectionTypeNameToBaseTypeNameMappings.Add(typeNameToBaseTypeNameMapping);
}
#if NET
[return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicConstructors)]
#endif
public static Type FindRcwTypeByNameCached(string runtimeClassName)
{
// Try to get the given type name. If it is not found, the type might have been trimmed.
// Due to that, check if one of the base types exists and if so use that instead for the RCW type.
var rcwType = FindTypeByNameCached(runtimeClassName);
if (rcwType is null)
{
rcwType = baseRcwTypeCache.GetOrAdd(runtimeClassName,
#if NET
[return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicConstructors)]
#endif
(runtimeClassName) =>
{
var resolvedBaseType = projectionTypeNameToBaseTypeNameMappings.Find((dict) => dict.ContainsKey(runtimeClassName))?[runtimeClassName];
return resolvedBaseType is not null ? FindRcwTypeByNameCached(resolvedBaseType) : null;
});
}
return rcwType;
}
/// <summary>
/// Parses and loads the given type name, if not found in the cache.
/// </summary>
/// <param name="runtimeClassName">The runtime class name to attempt to parse.</param>
/// <returns>The type, if found. Null otherwise</returns>
#if NET
[return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicConstructors)]
#endif
public static Type FindTypeByNameCached(string runtimeClassName)
{
return typeNameCache.GetOrAdd(runtimeClassName,
#if NET
[return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicConstructors)]
#endif
(runtimeClassName) =>
{
Type implementationType = null;
try
{
implementationType = FindTypeByName(runtimeClassName.AsSpan()).type;
}
catch (Exception)
{
}
return implementationType;
});
}
/// <summary>
/// Parse the first full type name within the provided span.
/// </summary>
/// <param name="runtimeClassName">The runtime class name to attempt to parse.</param>
/// <returns>A tuple containing the resolved type and the index of the end of the resolved type name.</returns>
public static (Type type, int remaining) FindTypeByName(ReadOnlySpan<char> runtimeClassName)
{
// Assume that anonymous types are expando objects, whether declared 'dynamic' or not.
// It may be necessary to detect otherwise and return System.Object.
if (runtimeClassName.StartsWith("<>f__AnonymousType".AsSpan(), StringComparison.Ordinal))
{
return (typeof(System.Dynamic.ExpandoObject), 0);
}
// PropertySet and ValueSet can return IReference<String> but Nullable<String> is illegal
else if (runtimeClassName.CompareTo("Windows.Foundation.IReference`1<String>".AsSpan(), StringComparison.Ordinal) == 0)
{
return (typeof(ABI.System.Nullable_string), 0);
}
else if (runtimeClassName.CompareTo("Windows.Foundation.IReference`1<Windows.UI.Xaml.Interop.TypeName>".AsSpan(), StringComparison.Ordinal) == 0)
{
return (typeof(ABI.System.Nullable_Type), 0);
}
else
{
var (genericTypeName, genericTypes, remaining) = ParseGenericTypeName(runtimeClassName);
if (genericTypeName == null)
{
return (null, -1);
}
return (FindTypeByNameCore(genericTypeName, genericTypes), remaining);
}
}
/// <summary>
/// Resolve a type from the given simple type name and the provided generic parameters.
/// </summary>
/// <param name="runtimeClassName">The simple type name.</param>
/// <param name="genericTypes">The generic parameters.</param>
/// <returns>The resolved (and instantiated if generic) type.</returns>
/// <remarks>
/// We look up the type dynamically because at this point in the stack we can't know
/// the full type closure of the application.
/// </remarks>
#if NET
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode",
Justification = "Any types which are trimmed are not used by user code and there is fallback logic to handle that.")]
[return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicConstructors)]
#endif
private static Type FindTypeByNameCore(string runtimeClassName, Type[] genericTypes)
{
Type resolvedType = Projections.FindCustomTypeForAbiTypeName(runtimeClassName);
if (resolvedType is null)
{
if (genericTypes is null)
{
Type primitiveType = ResolvePrimitiveType(runtimeClassName);
if (primitiveType is not null)
{
return primitiveType;
}
}
foreach (var assembly in projectionAssemblies)
{
Type type = assembly.GetType(runtimeClassName);
if (type is not null)
{
resolvedType = type;
break;
}
}
}
if (resolvedType is null)
{
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
Type type = assembly.GetType(runtimeClassName);
if (type is not null)
{
resolvedType = type;
break;
}
}
}
if (resolvedType is not null)
{
if (genericTypes != null)
{
if(resolvedType == typeof(global::System.Nullable<>) && genericTypes[0].IsDelegate())
{
return typeof(ABI.System.Nullable_Delegate<>).MakeGenericType(genericTypes);
}
resolvedType = resolvedType.MakeGenericType(genericTypes);
}
return resolvedType;
}
Debug.WriteLine($"FindTypeByNameCore: Unable to find a type named '{runtimeClassName}'");
return null;
}
public static Type ResolvePrimitiveType(string primitiveTypeName)
{
return primitiveTypeName switch
{
"UInt8" => typeof(byte),
"Int8" => typeof(sbyte),
"UInt16" => typeof(ushort),
"Int16" => typeof(short),
"UInt32" => typeof(uint),
"Int32" => typeof(int),
"UInt64" => typeof(ulong),
"Int64" => typeof(long),
"Boolean" => typeof(bool),
"String" => typeof(string),
"Char" => typeof(char),
"Char16" => typeof(char),
"Single" => typeof(float),
"Double" => typeof(double),
"Guid" => typeof(Guid),
"Object" => typeof(object),
"TimeSpan" => typeof(TimeSpan),
_ => null
};
}
/// <summary>
/// Parses a type name from the start of a span including its generic parameters.
/// </summary>
/// <param name="partialTypeName">A span starting with a type name to parse.</param>
/// <returns>Returns a tuple containing the simple type name of the type, and generic type parameters if they exist, and the index of the end of the type name in the span.</returns>
private static (string genericTypeName, Type[] genericTypes, int remaining) ParseGenericTypeName(ReadOnlySpan<char> partialTypeName)
{
int possibleEndOfSimpleTypeName = partialTypeName.IndexOfAny(',', '>');
int endOfSimpleTypeName = partialTypeName.Length;
if (possibleEndOfSimpleTypeName != -1)
{
endOfSimpleTypeName = possibleEndOfSimpleTypeName;
}
var typeName = partialTypeName.Slice(0, endOfSimpleTypeName);
// If the type name doesn't contain a '`', then it isn't a generic type
// so we can return before starting to parse the generic type list.
if (!typeName.Contains("`".AsSpan(), StringComparison.Ordinal))
{
return (typeName.ToString(), null, endOfSimpleTypeName);
}
int genericTypeListStart = partialTypeName.IndexOf('<');
var genericTypeName = partialTypeName.Slice(0, genericTypeListStart);
var remainingTypeName = partialTypeName.Slice(genericTypeListStart + 1);
int remainingIndex = genericTypeListStart + 1;
List<Type> genericTypes = new List<Type>();
while (true)
{
// Resolve the generic type argument at this point in the parameter list.
var (genericType, endOfGenericArgument) = FindTypeByName(remainingTypeName);
if (genericType == null)
{
return (null, null, -1);
}
remainingIndex += endOfGenericArgument;
genericTypes.Add(genericType);
remainingTypeName = remainingTypeName.Slice(endOfGenericArgument);
if (remainingTypeName[0] == ',')
{
// Skip the comma and the space in the type name.
remainingIndex += 2;
remainingTypeName = remainingTypeName.Slice(2);
continue;
}
else if (remainingTypeName[0] == '>')
{
// Skip the space after nested '>'
var skip = (remainingTypeName.Length > 1 && remainingTypeName[1] == ' ') ? 2 : 1;
remainingIndex += skip;
remainingTypeName = remainingTypeName.Slice(skip);
break;
}
else
{
throw new InvalidOperationException("The provided type name is invalid.");
}
}
return (genericTypeName.ToString(), genericTypes.ToArray(), partialTypeName.Length - remainingTypeName.Length);
}
struct VisitedType
{
public Type Type { get; set; }
public bool Covariant { get; set; }
}
/// <summary>
/// Tracker for visited types when determining a WinRT interface to use as the type name.
/// Only used when GetNameForType is called with <see cref="TypeNameGenerationFlags.NoCustomTypeName"/>.
/// </summary>
private static readonly ThreadLocal<Stack<VisitedType>> VisitedTypes = new ThreadLocal<Stack<VisitedType>>(() => new Stack<VisitedType>());
public static string GetNameForType(Type type, TypeNameGenerationFlags flags)
{
if (type is null)
{
return string.Empty;
}
StringBuilder nameBuilder = new StringBuilder();
if (TryAppendTypeName(type, nameBuilder, flags))
{
return nameBuilder.ToString();
}
return null;
}
private static bool TryAppendSimpleTypeName(Type type, StringBuilder builder, TypeNameGenerationFlags flags)
{
if (type.IsPrimitive || type == typeof(string) || type == typeof(Guid) || type == typeof(TimeSpan))
{
if ((flags & TypeNameGenerationFlags.GenerateBoxedName) != 0)
{
builder.Append("Windows.Foundation.IReference`1<");
if (!TryAppendSimpleTypeName(type, builder, flags & ~TypeNameGenerationFlags.GenerateBoxedName))
{
return false;
}
builder.Append('>');
return true;
}
if (type == typeof(byte))
{
builder.Append("UInt8");
}
else if (type == typeof(sbyte))
{
builder.Append("Int8");
}
else
{
builder.Append(type.Name);
}
}
else if (type == typeof(object))
{
builder.Append("Object");
}
else
{
var projectedAbiTypeName = Projections.FindCustomAbiTypeNameForType(type);
if (projectedAbiTypeName is object)
{
builder.Append(projectedAbiTypeName);
}
else if (Projections.IsTypeWindowsRuntimeType(type))
{
builder.Append(type.FullName);
}
else if ((flags & TypeNameGenerationFlags.NoCustomTypeName) != 0)
{
return TryAppendWinRTInterfaceNameForType(type, builder, flags);
}
else
{
builder.Append(type.FullName);
}
}
return true;
}
private static bool TryAppendWinRTInterfaceNameForType(Type type, StringBuilder builder, TypeNameGenerationFlags flags)
{
Debug.Assert((flags & TypeNameGenerationFlags.NoCustomTypeName) != 0);
Debug.Assert(!type.IsGenericTypeDefinition);
var visitedTypes = VisitedTypes.Value;
if (visitedTypes.Any(visited => visited.Type == type))
{
// In this case, we've already visited the type when recursing through generic parameters.
// Try to fall back to object if the parameter is covariant and the argument is compatable with object.
// Otherwise there's no valid type name.
if (visitedTypes.Peek().Covariant && !type.IsValueType)
{
builder.Append("Object");
return true;
}
return false;
}
else
{
visitedTypes.Push(new VisitedType { Type = type });
Type interfaceTypeToUse = null;
foreach (var iface in type.GetInterfaces())
{
if (Projections.IsTypeWindowsRuntimeType(iface))
{
if (interfaceTypeToUse is null || iface.IsAssignableFrom(interfaceTypeToUse))
{
interfaceTypeToUse = iface;
}
}
}
bool success = false;
if (interfaceTypeToUse is object)
{
success = TryAppendTypeName(interfaceTypeToUse, builder, flags);
}
visitedTypes.Pop();
return success;
}
}
private static bool TryAppendTypeName(Type type, StringBuilder builder, TypeNameGenerationFlags flags)
{
#if !NET
// We can't easily determine from just the type
// if the array is an "single dimension index from zero"-array in .NET Standard 2.0,
// so just approximate it.
// (Other array types will be blocked in other code-paths anyway where we have an object.)
if (type.IsArray && type.GetArrayRank() == 1)
#else
if (type.IsSZArray)
#endif
{
builder.Append("Windows.Foundation.IReferenceArray`1<");
if (TryAppendTypeName(type.GetElementType(), builder, flags & ~TypeNameGenerationFlags.GenerateBoxedName))
{
builder.Append('>');
return true;
}
return true;
}
if (!type.IsGenericType || type.IsGenericTypeDefinition)
{
return TryAppendSimpleTypeName(type, builder, flags);
}
if ((flags & TypeNameGenerationFlags.NoCustomTypeName) != 0 && !Projections.IsTypeWindowsRuntimeType(type))
{
return TryAppendWinRTInterfaceNameForType(type, builder, flags);
}
Type definition = type.GetGenericTypeDefinition();
if (!TryAppendSimpleTypeName(definition, builder, flags))
{
return false;
}
builder.Append('<');
bool first = true;
Type[] genericTypeArguments = type.GetGenericArguments();
Type[] genericTypeParameters = definition.GetGenericArguments();
for (int i = 0; i < genericTypeArguments.Length; i++)
{
Type argument = genericTypeArguments[i];
if (argument.ContainsGenericParameters)
{
throw new ArgumentException(nameof(type));
}
if (!first)
{
builder.Append(", ");
}
first = false;
if ((flags & TypeNameGenerationFlags.NoCustomTypeName) != 0)
{
VisitedTypes.Value.Push(new VisitedType
{
Type = type,
Covariant = (genericTypeParameters[i].GenericParameterAttributes & GenericParameterAttributes.VarianceMask) == GenericParameterAttributes.Covariant
});
}
bool success = TryAppendTypeName(argument, builder, flags & ~TypeNameGenerationFlags.GenerateBoxedName);
if ((flags & TypeNameGenerationFlags.NoCustomTypeName) != 0)
{
VisitedTypes.Value.Pop();
}
if (!success)
{
return false;
}
}
builder.Append('>');
return true;
}
}
}