-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathSymbolExtensions.cs
More file actions
791 lines (697 loc) · 32.3 KB
/
SymbolExtensions.cs
File metadata and controls
791 lines (697 loc) · 32.3 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Numerics;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;
using Microsoft.CodeAnalysis;
using TypeInfo = System.Reflection.TypeInfo;
namespace Microsoft.JavaScript.NodeApi.Generator;
/// <summary>
/// Extension methods for code-analysis symbol interfaces to support creation of fake
/// "symbolic" <see cref="Type" /> instances and members to represent compile-time types
/// during source generation.
/// </summary>
/// <remarks>
/// Symbolic types are abstract and consist of only public abstract members (no code).
/// They are used to construct lambda expressions from which C# code can be generated
/// (because expressions don't support code-analysis symbols).
/// </remarks>
internal static class SymbolExtensions
{
// The type cache must be thread-static (and initialized by each thread)
// because the build server may keep the analyzer in memory and re-use it
// across multiple compilations.
[ThreadStatic]
private static AssemblyBuilder? s_assemblyBuilder;
[ThreadStatic]
private static ModuleBuilder? s_moduleBuilder;
[ThreadStatic]
private static Dictionary<string, Type>? s_symbolicTypes;
private static int s_assemblyIndex = 0;
private static ModuleBuilder ModuleBuilder
{
get
{
if (s_moduleBuilder == null)
{
// Use a unique assembly name per thread.
string assemblyName = typeof(SymbolExtensions).FullName +
"_" + Interlocked.Increment(ref s_assemblyIndex);
s_assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(
new AssemblyName(assemblyName), AssemblyBuilderAccess.Run);
s_moduleBuilder = s_assemblyBuilder.DefineDynamicModule(
typeof(SymbolExtensions).Name);
}
return s_moduleBuilder;
}
}
private static Dictionary<string, Type> SymbolicTypes
{
get
{
s_symbolicTypes ??= new Dictionary<string, Type>();
return s_symbolicTypes;
}
}
/// <summary>
/// Clears the type cache to free up memory and get ready for another possible invocation.
/// The cache cannot be re-used across multiple invocations.
/// </summary>
public static void Reset()
{
s_assemblyBuilder = null;
s_moduleBuilder = null;
s_symbolicTypes = null;
}
/// <summary>
/// Gets either the actual type (if it is a system type) or a symbolic type
/// for the type symbol.
/// </summary>
public static Type AsType(this ITypeSymbol typeSymbol)
{
return typeSymbol.AsType(genericTypeParameters: null, buildType: true);
}
/// <summary>
/// Gets either the actual type (if it is a system type) or a symbolic type
/// for the type symbol.
/// </summary>
/// <param name="genericTypeParameters">Generic parameters from the containing type,
/// if the type is a nested type and the containing type is generic.</param>
/// <param name="buildType">True to force building (AKA emitting) the Type instance; if false
/// then an unbuilt TypeBuilder instance may be returned. (It is a subclass of Type, but
/// does not support some reflection operations.) Delayed type building is necessary in
/// complex object graphs where types have circular references to each other.</param>
private static Type AsType(
this ITypeSymbol typeSymbol,
Type[]? genericTypeParameters,
bool buildType = false)
{
if (typeSymbol is IArrayTypeSymbol arrayTypeSymbol)
{
if (arrayTypeSymbol.Rank != 1)
{
throw new NotSupportedException("Multi-dimensional arrays are not supported.");
}
return arrayTypeSymbol.ElementType.AsType(genericTypeParameters, buildType)
.MakeArrayType();
}
else if (typeSymbol is IPointerTypeSymbol pointerTypeSymbol)
{
return pointerTypeSymbol.PointedAtType.AsType(genericTypeParameters, buildType)
.MakePointerType();
}
if (typeSymbol is ITypeParameterSymbol typeParameterSymbol)
{
if (genericTypeParameters?.Length > typeParameterSymbol.Ordinal)
{
return genericTypeParameters[typeParameterSymbol.Ordinal];
}
else if (typeParameterSymbol.ContainingSymbol is IMethodSymbol methodSymbol)
{
#if NETFRAMEWORK || NETSTANDARD
// There's no .NET Framework API to make a generic method parameter type.
// But it isn't needed anyway: the calling method will not request it.
throw new InvalidOperationException(
$"Unknown generic type parameter {typeParameterSymbol} " +
$"in method {GetTypeSymbolFullName(typeParameterSymbol.ContainingType)}" +
$".{methodSymbol.Name}()");
#else
return Type.MakeGenericMethodParameter(typeParameterSymbol.Ordinal);
#endif
}
else
{
throw new InvalidOperationException(
$"Unknown generic type parameter {typeParameterSymbol} " +
$"in type {GetTypeSymbolFullName(typeParameterSymbol.ContainingType)}");
}
}
if (typeSymbol is not INamedTypeSymbol namedTypeSymbol)
{
throw new NotSupportedException($"Unnamed types are not supported: {typeSymbol}");
}
string typeFullName = GetTypeSymbolFullName(namedTypeSymbol);
ITypeSymbol[] genericArguments = namedTypeSymbol.TypeArguments.ToArray();
Type? systemType = GetSystemType(namedTypeSymbol);
if (systemType != null)
{
if (genericArguments.Length > 0)
{
systemType = systemType.MakeGenericType(genericArguments
.Select((t) => t.AsType(genericTypeParameters, buildType))
.ToArray());
}
return systemType;
}
// Generating the containing type will also generate the nested type,
// so it should be found in the SymbolicTypes dictionary afterward.
typeSymbol.ContainingType?.AsType(genericTypeParameters, buildType);
if (SymbolicTypes.TryGetValue(typeFullName, out Type? symbolicType))
{
if (genericArguments.Length > 0)
{
symbolicType = symbolicType.MakeGenericType(genericArguments
.Select((t) => t.AsType(genericTypeParameters, buildType))
.ToArray());
}
if (buildType && symbolicType is TypeBuilder typeBuilder)
{
BuildReferencedTypes((INamedTypeSymbol)typeSymbol);
symbolicType = typeBuilder.CreateTypeInfo()!;
SymbolicTypes[typeFullName] = symbolicType;
}
return symbolicType;
}
symbolicType = typeSymbol.TypeKind switch
{
TypeKind.Enum => BuildSymbolicEnumType(namedTypeSymbol, typeFullName),
TypeKind.Class or TypeKind.Interface or TypeKind.Struct or TypeKind.Delegate =>
BuildSymbolicObjectType(
namedTypeSymbol, typeFullName, genericTypeParameters, buildType),
_ => throw new NotSupportedException(
$"Type kind not supported: {typeSymbol.TypeKind}"),
};
// Update the map entry to refer to the built type instead of the type builder.
SymbolicTypes[typeFullName] = symbolicType;
if (genericArguments.Length > 0)
{
symbolicType = symbolicType.MakeGenericType(genericArguments
.Select((t) => t.AsType(genericTypeParameters, buildType))
.ToArray());
}
return symbolicType;
}
/// <summary>
/// Gets the full name of a type symbol. It is the same as <see cref="Type.FullName" />,
/// but this is used before the Type instance is built from the type symbol.
/// </summary>
private static string GetTypeSymbolFullName(INamedTypeSymbol typeSymbol)
{
string ns = typeSymbol.ContainingType != null ?
GetTypeSymbolFullName(typeSymbol.ContainingType) :
typeSymbol.ContainingNamespace.IsGlobalNamespace ?
"" : typeSymbol.ContainingNamespace.ToString()!;
string name = (ns.Length > 0 ? ns + "." : "") + typeSymbol.Name;
if (typeSymbol.TypeParameters.Length > 0)
{
name += "`" + typeSymbol.TypeParameters.Length;
}
return name;
}
private static TypeInfo BuildSymbolicEnumType(
INamedTypeSymbol typeSymbol,
string typeFullName)
{
Type underlyingType = typeSymbol.EnumUnderlyingType!.AsType();
EnumBuilder enumBuilder = ModuleBuilder.DefineEnum(
typeFullName, TypeAttributes.Public, underlyingType);
foreach (IFieldSymbol fieldSymbol in typeSymbol.GetMembers().OfType<IFieldSymbol>())
{
enumBuilder.DefineLiteral(fieldSymbol.Name, fieldSymbol.ConstantValue);
}
return enumBuilder.CreateTypeInfo()!;
}
private static TypeAttributes GetTypeAttributes(ITypeSymbol typeSymbol)
{
TypeAttributes attributes = TypeAttributes.Public;
switch (typeSymbol.TypeKind)
{
case TypeKind.Interface:
attributes |= TypeAttributes.Interface | TypeAttributes.Abstract;
break;
case TypeKind.Class:
if (typeSymbol.IsAbstract || typeSymbol.IsStatic)
{
attributes |= TypeAttributes.Abstract;
}
if (typeSymbol.IsSealed || typeSymbol.IsStatic)
{
attributes |= TypeAttributes.Sealed;
}
break;
case TypeKind.Struct:
attributes |= TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit;
break;
case TypeKind.Delegate:
attributes |= TypeAttributes.Sealed;
break;
case TypeKind.Enum:
attributes |= TypeAttributes.Abstract;
break;
}
return attributes;
}
private static Type BuildSymbolicObjectType(
INamedTypeSymbol typeSymbol,
string typeFullName,
Type[]? genericTypeParameters,
bool buildType)
{
TypeBuilder typeBuilder;
Type? baseType = typeSymbol.BaseType?.AsType(genericTypeParameters, buildType);
// A base type might have had a reference to this type and therefore already defined it.
if (SymbolicTypes.TryGetValue(typeFullName, out Type? thisType))
{
if (thisType is not TypeBuilder)
{
// The type is already fully built.
return thisType;
}
typeBuilder = (TypeBuilder)thisType;
}
else
{
typeBuilder = ModuleBuilder.DefineType(
name: typeFullName,
GetTypeAttributes(typeSymbol),
parent: baseType);
if (typeSymbol.TypeParameters.Length > 0)
{
genericTypeParameters ??= [];
genericTypeParameters = typeBuilder.DefineGenericParameters(
typeSymbol.TypeParameters.Select((p) => p.Name).ToArray());
}
// Add the type builder to the map while building it, to support circular references.
SymbolicTypes.Add(typeFullName, typeBuilder);
BuildSymbolicTypeMembers(typeSymbol, typeBuilder, genericTypeParameters);
// Preserve JS attributes, which might be referenced by the marshaller.
foreach (AttributeData attribute in typeSymbol.GetAttributes())
{
if (attribute.AttributeClass!.ContainingNamespace.ToString()!.StartsWith(
typeof(JSExportAttribute).Namespace!, StringComparison.Ordinal))
{
Type attributeType = attribute.AttributeClass.AsType();
ConstructorInfo constructor = attributeType.GetConstructor(
attribute.ConstructorArguments.Select((a) => a.Type!.AsType()).ToArray()) ??
throw new MissingMemberException(
$"Constructor not found for attribute: {attributeType.Name}");
CustomAttributeBuilder attributeBuilder = new(
constructor,
attribute.ConstructorArguments.Select((a) => a.Value).ToArray(),
attribute.NamedArguments.Select((a) =>
GetAttributeProperty(attributeType, a.Key)).ToArray(),
attribute.NamedArguments.Select((a) => a.Value.Value).ToArray()!);
typeBuilder.SetCustomAttribute(attributeBuilder);
}
}
static PropertyInfo GetAttributeProperty(Type type, string name)
=> type.GetProperty(name, BindingFlags.Public | BindingFlags.Instance) ??
throw new MissingMemberException(
$"Property {name} not found on attribute {type.Name}.");
}
if (!buildType)
{
return typeBuilder;
}
// Ensure the base type and interfaces are built before building the derived type.
BuildReferencedTypes(typeSymbol);
// Ensure this type is only built once.
if (SymbolicTypes.TryGetValue(typeFullName, out thisType) && thisType is not TypeBuilder)
{
return thisType;
}
try
{
return typeBuilder.CreateTypeInfo()!;
}
catch (Exception ex)
{
throw new InvalidOperationException(
$"Failed to create type info for type: {typeSymbol.Name}", ex);
}
}
/// <summary>
/// Gets the system type for a type symbol, if the type symbol represents a type that is already
/// loaded in the current process and therefore doesn't need to be built as a symbolic type.
/// </summary>
private static Type? GetSystemType(INamedTypeSymbol typeSymbol)
{
string typeFullName = GetTypeSymbolFullName(typeSymbol);
Type? systemType = typeof(object).Assembly.GetType(typeFullName) ??
typeof(JSValue).Assembly.GetType(typeFullName) ??
typeof(BigInteger).Assembly.GetType(typeFullName) ?? // System.Runtime.Numerics
typeof(Stack<>).Assembly.GetType(typeFullName) ?? // System.Collections
typeof(Expression).Assembly.GetType(typeFullName) ?? // System.Linq.Expressions
typeof(System.Collections.ObjectModel.ReadOnlyDictionary<,>)
.Assembly.GetType(typeFullName); // System.ObjectModel
return systemType;
}
/// <summary>
/// Ensures that a type symbol's type arguments (if any), base type, interface types,
/// property types, and method parameter and return types are built before building the
/// target type.
/// </summary>
/// <param name="typeSymbol">The symbol that is about to be built as a type.</param>
/// <param name="referencingSymbols">Optional list of types that led to referencing this one,
/// used to prevent infinite recursion.</param>
private static void BuildReferencedTypes(
INamedTypeSymbol typeSymbol, IEnumerable<INamedTypeSymbol>? referencingSymbols = null)
{
static void BuildType(
INamedTypeSymbol typeSymbol,
IEnumerable<INamedTypeSymbol> referencingSymbols)
{
// Recursively build the types that the current type references.
BuildReferencedTypes(typeSymbol, referencingSymbols);
// Now build the current type (if not already built).
string typeFullName = GetTypeSymbolFullName(typeSymbol);
if (SymbolicTypes.TryGetValue(typeFullName, out Type? type) &&
type is TypeBuilder typeBuilder)
{
try
{
typeBuilder.CreateTypeInfo();
}
catch (Exception ex)
{
throw new InvalidOperationException(
$"Failed to create type info for type: {typeSymbol.Name}", ex);
}
}
}
if (referencingSymbols?.Any(
(s) => SymbolEqualityComparer.Default.Equals(s, typeSymbol)) == true)
{
// Skip self-referential type symbols.
return;
}
referencingSymbols = (referencingSymbols ?? []).Append(typeSymbol);
foreach (INamedTypeSymbol typeArgSymbol in
typeSymbol.TypeArguments.OfType<INamedTypeSymbol>())
{
BuildType(typeArgSymbol, referencingSymbols);
}
if (GetSystemType(typeSymbol) != null)
{
// The base type, interface type(s), and parameter types must be already loaded.
return;
}
if (typeSymbol.BaseType != null)
{
BuildType(typeSymbol.BaseType, referencingSymbols);
}
foreach (INamedTypeSymbol interfaceTypeSymbol in typeSymbol.Interfaces)
{
BuildType(interfaceTypeSymbol, referencingSymbols);
}
// This also covers property and event types via their get/set/add/remove methods.
foreach (INamedTypeSymbol? parameterTypeSymbol in typeSymbol.GetMembers()
.OfType<IMethodSymbol>()
.Where((m) => m.DeclaredAccessibility == Accessibility.Public)
.SelectMany((m) => m.Parameters.Select((p) => p.Type).Append(m.ReturnType))
.OfType<INamedTypeSymbol>()
.Distinct(SymbolEqualityComparer.Default).Cast<INamedTypeSymbol?>())
{
BuildType(parameterTypeSymbol!, referencingSymbols);
}
}
private static void BuildSymbolicTypeMembers(
ITypeSymbol typeSymbol,
TypeBuilder typeBuilder,
Type[]? genericTypeParameters)
{
foreach (Type interfaceType in typeSymbol.Interfaces.Select(
(i) => i.AsType(genericTypeParameters)))
{
typeBuilder.AddInterfaceImplementation(interfaceType);
}
foreach (ISymbol memberSymbol in typeSymbol.GetMembers()
.Where((m) => m.DeclaredAccessibility == Accessibility.Public ||
(m.DeclaredAccessibility == Accessibility.Private &&
(m is IMethodSymbol ms && ms.ExplicitInterfaceImplementations.Length > 0) ||
(m is IPropertySymbol ps && ps.ExplicitInterfaceImplementations.Length > 0))))
{
if (memberSymbol is IMethodSymbol constructorSymbol &&
constructorSymbol.MethodKind == MethodKind.Constructor)
{
BuildSymbolicConstructor(typeBuilder, constructorSymbol, genericTypeParameters);
}
else if (memberSymbol is IMethodSymbol methodSymbol &&
(methodSymbol.MethodKind == MethodKind.Ordinary ||
methodSymbol.MethodKind == MethodKind.ExplicitInterfaceImplementation ||
methodSymbol.MethodKind == MethodKind.DelegateInvoke))
{
BuildSymbolicMethod(typeBuilder, methodSymbol, genericTypeParameters);
}
else if (memberSymbol is IPropertySymbol propertySymbol)
{
BuildSymbolicProperty(typeBuilder, propertySymbol, genericTypeParameters);
}
else if (memberSymbol is IEventSymbol eventSymbol)
{
// TODO: Events
}
else if (memberSymbol is IFieldSymbol fieldSymbol)
{
// TODO: Fields (at least const fields)
}
else if (memberSymbol is INamedTypeSymbol nestedTypeSymbol)
{
TypeAttributes attributes = GetTypeAttributes(nestedTypeSymbol);
attributes &= ~TypeAttributes.Public;
attributes |= TypeAttributes.NestedPublic;
TypeBuilder nestedTypeBuilder = typeBuilder.DefineNestedType(
nestedTypeSymbol.Name,
attributes,
parent: nestedTypeSymbol.TypeKind == TypeKind.Enum ? typeof(Enum) : null);
// TODO: Handle nested enum members (fields).
BuildSymbolicTypeMembers(
nestedTypeSymbol, nestedTypeBuilder, genericTypeParameters);
}
}
}
private static ConstructorBuilder BuildSymbolicConstructor(
TypeBuilder typeBuilder,
IMethodSymbol constructorSymbol,
Type[]? genericTypeParameters)
{
bool isDelegateConstructor = typeBuilder.BaseType == typeof(MulticastDelegate);
ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(
MethodAttributes.Public | (isDelegateConstructor ?
MethodAttributes.RTSpecialName | MethodAttributes.HideBySig : default),
CallingConventions.HasThis,
constructorSymbol.Parameters.Select(
(p) => p.Type.AsType(genericTypeParameters, buildType: false)).ToArray());
IReadOnlyList<IParameterSymbol> parameters = constructorSymbol.Parameters;
for (int i = 0; i < parameters.Count; i++)
{
// The parameter index is offset by 1.
constructorBuilder.DefineParameter(i + 1, ParameterAttributes.None, parameters[i].Name);
}
if (isDelegateConstructor)
{
// Delegate constructors are implemented by the runtime.
constructorBuilder.SetImplementationFlags(
MethodImplAttributes.Runtime | MethodImplAttributes.Managed);
}
else
{
// Constructors cannot be abstract; emit a minimal body.
constructorBuilder.GetILGenerator().Emit(OpCodes.Ret);
}
return constructorBuilder;
}
private static void BuildSymbolicMethod(
TypeBuilder typeBuilder,
IMethodSymbol methodSymbol,
Type[]? genericTypeParameters)
{
bool isDelegateMethod = typeBuilder.BaseType == typeof(MulticastDelegate);
// All nonstatic methods are declared virtual on symbolic types.
// This allows any struct/class methods to implement interface methods.
MethodAttributes attributes =
(methodSymbol.DeclaredAccessibility == Accessibility.Public ?
MethodAttributes.Public : MethodAttributes.Private) |
(methodSymbol.IsStatic ? MethodAttributes.Static : MethodAttributes.Virtual) |
(methodSymbol.IsAbstract ? MethodAttributes.Abstract : default) |
(methodSymbol.ExplicitInterfaceImplementations.Length > 0 ?
MethodAttributes.Final : default) |
(isDelegateMethod ? MethodAttributes.HideBySig : default);
MethodBuilder methodBuilder = typeBuilder.DefineMethod(
methodSymbol.Name,
attributes,
methodSymbol.IsStatic ? CallingConventions.Standard : CallingConventions.HasThis);
GenericTypeParameterBuilder[]? genericMethodParameters = null;
if (methodSymbol.TypeParameters.Length > 0)
{
genericMethodParameters = methodBuilder.DefineGenericParameters(
methodSymbol.TypeParameters.Select((p) => p.Name).ToArray());
}
Type[]? genericParameters =
genericTypeParameters == null ? genericMethodParameters :
genericMethodParameters == null ? genericTypeParameters :
genericTypeParameters.Concat(genericMethodParameters).ToArray();
methodBuilder.SetReturnType(
methodSymbol.ReturnType.AsType(genericParameters, buildType: false));
methodBuilder.SetParameters(methodSymbol.Parameters.Select(
(p) => p.Type.AsType(genericParameters, buildType: false)).ToArray());
BuildSymbolicParameters(methodBuilder, methodSymbol.Parameters);
if (isDelegateMethod)
{
// Delegate invoke methods are implemented by the runtime.
methodBuilder.SetImplementationFlags(
MethodImplAttributes.Runtime | MethodImplAttributes.Managed);
}
else if (!methodSymbol.IsAbstract)
{
// Emit a minimal method body.
methodBuilder.GetILGenerator().Emit(OpCodes.Ret);
}
if (methodSymbol.ExplicitInterfaceImplementations.Length > 0)
{
MethodInfo interfaceMethod =
methodSymbol.ExplicitInterfaceImplementations[0].AsMethodInfo();
typeBuilder.DefineMethodOverride(methodBuilder, interfaceMethod);
}
}
private static void BuildSymbolicProperty(
TypeBuilder typeBuilder,
IPropertySymbol propertySymbol,
Type[]? genericTypeParameters)
{
MethodAttributes attributes = MethodAttributes.SpecialName |
(propertySymbol.DeclaredAccessibility == Accessibility.Public ?
MethodAttributes.Public : MethodAttributes.Private) |
(propertySymbol.IsStatic ? MethodAttributes.Static : MethodAttributes.Virtual) |
(propertySymbol.IsAbstract ? MethodAttributes.Abstract : default) |
(propertySymbol.IsVirtual ? MethodAttributes.Virtual : default) |
(propertySymbol.ExplicitInterfaceImplementations.Length > 0 ?
MethodAttributes.Final : default);
PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(
propertySymbol.Name,
PropertyAttributes.None,
propertySymbol.Type.AsType(genericTypeParameters, buildType: false),
propertySymbol.Parameters.Select(
(p) => p.Type.AsType(genericTypeParameters, buildType: false)).ToArray());
if (propertySymbol.GetMethod != null)
{
MethodBuilder getMethodBuilder = typeBuilder.DefineMethod(
propertySymbol.GetMethod.Name,
attributes,
propertySymbol.IsStatic ? CallingConventions.Standard : CallingConventions.HasThis,
propertySymbol.GetMethod.ReturnType.AsType(genericTypeParameters, buildType: false),
propertySymbol.GetMethod.Parameters.Select(
(p) => p.Type.AsType(genericTypeParameters, buildType: false)).ToArray());
BuildSymbolicParameters(getMethodBuilder, propertySymbol.GetMethod.Parameters);
if (!propertySymbol.IsAbstract) getMethodBuilder.GetILGenerator().Emit(OpCodes.Ret);
propertyBuilder.SetGetMethod(getMethodBuilder);
if (propertySymbol.ExplicitInterfaceImplementations.Length > 0)
{
MethodInfo interfaceGetMethod =
propertySymbol.ExplicitInterfaceImplementations[0].GetMethod!.AsMethodInfo();
typeBuilder.DefineMethodOverride(getMethodBuilder, interfaceGetMethod);
}
}
if (propertySymbol.SetMethod != null)
{
MethodBuilder setMethodBuilder = typeBuilder.DefineMethod(
propertySymbol.SetMethod.Name,
attributes,
propertySymbol.IsStatic ? CallingConventions.Standard : CallingConventions.HasThis,
propertySymbol.SetMethod.ReturnType.AsType(genericTypeParameters, buildType: false),
propertySymbol.SetMethod.Parameters.Select(
(p) => p.Type.AsType(genericTypeParameters, buildType: false)).ToArray());
BuildSymbolicParameters(setMethodBuilder, propertySymbol.SetMethod.Parameters);
if (!propertySymbol.IsAbstract) setMethodBuilder.GetILGenerator().Emit(OpCodes.Ret);
propertyBuilder.SetSetMethod(setMethodBuilder);
if (propertySymbol.ExplicitInterfaceImplementations.Length > 0)
{
MethodInfo interfaceSetMethod =
propertySymbol.ExplicitInterfaceImplementations[0].SetMethod!.AsMethodInfo();
typeBuilder.DefineMethodOverride(setMethodBuilder, interfaceSetMethod);
}
}
}
private static void BuildSymbolicParameters(
MethodBuilder methodBuilder, IReadOnlyList<IParameterSymbol> parameters)
{
for (int i = 0; i < parameters.Count; i++)
{
ParameterAttributes attributes = parameters[i].RefKind switch
{
RefKind.In => ParameterAttributes.In,
RefKind.Out => ParameterAttributes.Out,
RefKind.Ref => ParameterAttributes.In | ParameterAttributes.Out,
_ => ParameterAttributes.None,
};
// Position here is offset by one because the return parameter is at 0.
methodBuilder.DefineParameter(i + 1, attributes, parameters[i].Name);
}
}
/// <summary>
/// Gets real or symbolic constructor info for a method symbol.
/// </summary>
public static ConstructorInfo AsConstructorInfo(this IMethodSymbol methodSymbol)
{
if (methodSymbol.MethodKind != MethodKind.Constructor)
{
throw new ArgumentException("Method is not a constructor.", nameof(methodSymbol));
}
Type type = methodSymbol.ContainingType.AsType();
Type[] parameterTypes = methodSymbol.Parameters
.Select((p) => p.Type.AsType(type.GenericTypeArguments, buildType: true))
.ToArray();
BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance;
ConstructorInfo? constructorInfo = type.GetConstructors(bindingFlags)
.FirstOrDefault((c) => c.GetParameters().Select((p) => p.ParameterType.FullName)
.SequenceEqual(parameterTypes.Select((t) => t.FullName)));
return constructorInfo ?? throw new InvalidOperationException(
$"Constructor not found for type: {type.Name}");
}
/// <summary>
/// Gets real or symbolic method info for a method symbol.
/// </summary>
public static MethodInfo AsMethodInfo(this IMethodSymbol methodSymbol)
{
Type type = methodSymbol.ContainingType.AsType();
// Ensure method parameter and return types are built.
Type[] typeParameters = type.GetGenericArguments();
#if NETFRAMEWORK || NETSTANDARD
// .NET Framework cannot make generic method parameter types.
IEnumerable<Type> methodTypeParameters = [];
#else
IEnumerable<Type> methodTypeParameters = methodSymbol.TypeParameters.Select(
(t) => t.AsType(typeParameters, buildType: true));
#endif
typeParameters = typeParameters.Concat(methodTypeParameters).ToArray();
Type[] parameterTypes = methodSymbol.Parameters
.Select((p) => p.Type.AsType(typeParameters, buildType: true))
.ToArray();
Type returnType = methodSymbol.ReturnType.AsType(
type.GenericTypeArguments, buildType: true);
BindingFlags bindingFlags = BindingFlags.Public |
(methodSymbol.IsStatic ? BindingFlags.Static : BindingFlags.Instance);
MethodInfo? methodInfo = type.GetMethods(bindingFlags)
.FirstOrDefault((m) => m.Name == methodSymbol.Name &&
m.GetParameters().Select((p) => p.ParameterType.FullName)
.SequenceEqual(parameterTypes.Select((t) => t.FullName)) &&
m.ReturnType.FullName == returnType.FullName);
return methodInfo ?? throw new InvalidOperationException(
$"Method not found: {type.Name}.{methodSymbol.Name}");
}
/// <summary>
/// Gets real or symbolic property info for a property symbol.
/// </summary>
public static PropertyInfo AsPropertyInfo(this IPropertySymbol propertySymbol)
{
Type type = propertySymbol.ContainingType.AsType();
Type[] parameterTypes = propertySymbol.Parameters.Select(
(p) => p.Type.AsType(type.GenericTypeArguments, buildType: true)).ToArray();
BindingFlags bindingFlags = BindingFlags.Public |
(propertySymbol.IsStatic ? BindingFlags.Static : BindingFlags.Instance);
PropertyInfo? propertyInfo = type.GetProperty(
propertySymbol.Name,
bindingFlags,
binder: null,
returnType: null,
parameterTypes,
modifiers: null);
return propertyInfo ?? throw new InvalidOperationException(
$"Property not found: {type.Name}.{propertySymbol.Name}");
}
}