-
Notifications
You must be signed in to change notification settings - Fork 94
/
Generator.cs
1617 lines (1401 loc) · 72.7 KB
/
Generator.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
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. See LICENSE file in the project root for full license information.
namespace Microsoft.Windows.CsWin32;
/// <summary>
/// The core of the source generator.
/// </summary>
[DebuggerDisplay("{" + nameof(DebuggerDisplayString) + ",nq}")]
public partial class Generator : IGenerator, IDisposable
{
private readonly TypeSyntaxSettings generalTypeSettings;
private readonly TypeSyntaxSettings fieldTypeSettings;
private readonly TypeSyntaxSettings delegateSignatureTypeSettings;
private readonly TypeSyntaxSettings enumTypeSettings;
private readonly TypeSyntaxSettings fieldOfHandleTypeDefTypeSettings;
private readonly TypeSyntaxSettings externSignatureTypeSettings;
private readonly TypeSyntaxSettings externReleaseSignatureTypeSettings;
private readonly TypeSyntaxSettings comSignatureTypeSettings;
private readonly TypeSyntaxSettings extensionMethodSignatureTypeSettings;
private readonly TypeSyntaxSettings functionPointerTypeSettings;
private readonly TypeSyntaxSettings errorMessageTypeSettings;
private readonly ClassDeclarationSyntax comHelperClass;
/// <summary>
/// The struct with one type parameter used to represent a variable-length inline array.
/// </summary>
private readonly StructDeclarationSyntax variableLengthInlineArrayStruct1;
/// <summary>
/// The struct with two type parameters used to represent a variable-length inline array.
/// This is useful when the exposed type parameter is C# unmanaged but runtime unblittable (i.e. <see langword="bool" /> and <see langword="char" />).
/// </summary>
private readonly StructDeclarationSyntax variableLengthInlineArrayStruct2;
private readonly Dictionary<string, IReadOnlyList<ISymbol>> findTypeSymbolIfAlreadyAvailableCache = new(StringComparer.Ordinal);
private readonly Rental<MetadataReader> metadataReader;
private readonly GeneratorOptions options;
private readonly CSharpCompilation? compilation;
private readonly CSharpParseOptions? parseOptions;
private readonly bool comIIDInterfacePredefined;
private readonly bool getDelegateForFunctionPointerGenericExists;
private readonly GeneratedCode committedCode = new();
private readonly GeneratedCode volatileCode;
private readonly IdentifierNameSyntax methodsAndConstantsClassName;
private readonly HashSet<string> injectedPInvokeHelperMethods = new();
private readonly HashSet<string> injectedPInvokeMacros = new();
private readonly Dictionary<TypeDefinitionHandle, bool> managedTypesCheck = new();
private bool needsWinRTCustomMarshaler;
private MethodDeclarationSyntax? sliceAtNullMethodDecl;
static Generator()
{
if (!TryFetchTemplate("PInvokeClassHelperMethods", null, out MemberDeclarationSyntax? member))
{
throw new GenerationFailedException("Missing embedded resource.");
}
PInvokeHelperMethods = ((ClassDeclarationSyntax)member).Members.OfType<MethodDeclarationSyntax>().ToDictionary(m => m.Identifier.ValueText, m => m);
if (!TryFetchTemplate("PInvokeClassMacros", null, out member))
{
throw new GenerationFailedException("Missing embedded resource.");
}
Win32SdkMacros = ((ClassDeclarationSyntax)member).Members.OfType<MethodDeclarationSyntax>().ToDictionary(m => m.Identifier.ValueText, m => m);
FetchTemplate("IVTable", null, out IVTableInterface);
FetchTemplate("IVTable`2", null, out IVTableGenericInterface);
}
/// <summary>
/// Initializes a new instance of the <see cref="Generator"/> class.
/// </summary>
/// <param name="metadataLibraryPath">The path to the winmd metadata to generate APIs from.</param>
/// <param name="docs">The API docs to include in the generated code.</param>
/// <param name="options">Options that influence the result of generation.</param>
/// <param name="compilation">The compilation that the generated code will be added to.</param>
/// <param name="parseOptions">The parse options that will be used for the generated code.</param>
public Generator(string metadataLibraryPath, Docs? docs, GeneratorOptions options, CSharpCompilation? compilation = null, CSharpParseOptions? parseOptions = null)
{
if (options is null)
{
throw new ArgumentNullException(nameof(options));
}
this.MetadataIndex = MetadataIndex.Get(metadataLibraryPath, compilation?.Options.Platform);
this.ApiDocs = docs;
this.metadataReader = MetadataIndex.GetMetadataReader(metadataLibraryPath);
this.options = options;
this.options.Validate();
this.compilation = compilation;
this.parseOptions = parseOptions;
this.volatileCode = new(this.committedCode);
// UnscopedRefAttribute may be emitted to work on downlevel *runtimes*, but we can't use it
// on downlevel *compilers*. Only .NET 8+ SDK compilers support it. Since we cannot detect
// compiler version, we use language version instead.
this.canUseUnscopedRef = this.parseOptions?.LanguageVersion >= (LanguageVersion)1100; // C# 11.0
this.canUseSpan = this.compilation?.GetTypeByMetadataName(typeof(Span<>).FullName) is not null;
this.canCallCreateSpan = this.compilation?.GetTypeByMetadataName(typeof(MemoryMarshal).FullName)?.GetMembers("CreateSpan").Any() is true;
this.canUseUnsafeAsRef = this.compilation?.GetTypeByMetadataName(typeof(Unsafe).FullName)?.GetMembers("Add").Any() is true;
this.canUseUnsafeAdd = this.compilation?.GetTypeByMetadataName(typeof(Unsafe).FullName)?.GetMembers("AsRef").Any() is true;
this.canUseUnsafeNullRef = this.compilation?.GetTypeByMetadataName(typeof(Unsafe).FullName)?.GetMembers("NullRef").Any() is true;
this.canUseUnsafeSkipInit = this.compilation?.GetTypeByMetadataName(typeof(Unsafe).FullName)?.GetMembers("SkipInit").Any() is true;
this.canUseUnmanagedCallersOnlyAttribute = this.compilation?.GetTypeByMetadataName("System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute") is not null;
this.canUseSetLastPInvokeError = this.compilation?.GetTypeByMetadataName("System.Runtime.InteropServices.Marshal")?.GetMembers("GetLastSystemError").IsEmpty is false;
this.unscopedRefAttributePredefined = this.FindTypeSymbolIfAlreadyAvailable("System.Diagnostics.CodeAnalysis.UnscopedRefAttribute") is not null;
this.runtimeFeatureClass = (INamedTypeSymbol?)this.FindTypeSymbolIfAlreadyAvailable("System.Runtime.CompilerServices.RuntimeFeature");
this.comIIDInterfacePredefined = this.FindTypeSymbolIfAlreadyAvailable($"{this.Namespace}.{IComIIDGuidInterfaceName}") is not null;
this.getDelegateForFunctionPointerGenericExists = this.compilation?.GetTypeByMetadataName(typeof(Marshal).FullName)?.GetMembers(nameof(Marshal.GetDelegateForFunctionPointer)).Any(m => m is IMethodSymbol { IsGenericMethod: true }) is true;
this.generateDefaultDllImportSearchPathsAttribute = this.compilation?.GetTypeByMetadataName(typeof(DefaultDllImportSearchPathsAttribute).FullName) is object;
if (this.FindTypeSymbolIfAlreadyAvailable("System.Runtime.Versioning.SupportedOSPlatformAttribute") is { } attribute)
{
this.generateSupportedOSPlatformAttributes = true;
AttributeData usageAttribute = attribute.GetAttributes().Single(att => att.AttributeClass?.Name == nameof(AttributeUsageAttribute));
var targets = (AttributeTargets)usageAttribute.ConstructorArguments[0].Value!;
this.generateSupportedOSPlatformAttributesOnInterfaces = (targets & AttributeTargets.Interface) == AttributeTargets.Interface;
}
// Convert some of our CanUse fields to preprocessor symbols so our templates can use them.
if (this.parseOptions is not null)
{
List<string> extraSymbols = new();
AddSymbolIf(this.canUseSpan, "canUseSpan");
AddSymbolIf(this.canCallCreateSpan, "canCallCreateSpan");
AddSymbolIf(this.canUseUnsafeAsRef, "canUseUnsafeAsRef");
AddSymbolIf(this.canUseUnsafeAdd, "canUseUnsafeAdd");
AddSymbolIf(this.canUseUnsafeNullRef, "canUseUnsafeNullRef");
AddSymbolIf(compilation?.GetTypeByMetadataName("System.Drawing.Point") is not null, "canUseSystemDrawing");
AddSymbolIf(this.IsFeatureAvailable(Feature.InterfaceStaticMembers), "canUseInterfaceStaticMembers");
AddSymbolIf(this.canUseUnscopedRef, "canUseUnscopedRef");
if (extraSymbols.Count > 0)
{
this.parseOptions = this.parseOptions.WithPreprocessorSymbols(this.parseOptions.PreprocessorSymbolNames.Concat(extraSymbols));
}
void AddSymbolIf(bool condition, string symbol)
{
if (condition)
{
extraSymbols.Add(symbol);
}
}
}
bool useComInterfaces = options.AllowMarshaling;
this.generalTypeSettings = new TypeSyntaxSettings(
this,
PreferNativeInt: this.LanguageVersion >= LanguageVersion.CSharp9,
PreferMarshaledTypes: false,
AllowMarshaling: options.AllowMarshaling,
QualifyNames: false);
this.fieldTypeSettings = this.generalTypeSettings with { QualifyNames = true, IsField = true };
this.delegateSignatureTypeSettings = this.generalTypeSettings with { QualifyNames = true };
this.enumTypeSettings = this.generalTypeSettings;
this.fieldOfHandleTypeDefTypeSettings = this.generalTypeSettings with { PreferNativeInt = false };
this.externSignatureTypeSettings = this.generalTypeSettings with { QualifyNames = true, PreferMarshaledTypes = options.AllowMarshaling };
this.externReleaseSignatureTypeSettings = this.externSignatureTypeSettings with { PreferNativeInt = false, PreferMarshaledTypes = false };
this.comSignatureTypeSettings = this.generalTypeSettings with { QualifyNames = true, PreferInOutRef = options.AllowMarshaling };
this.extensionMethodSignatureTypeSettings = this.generalTypeSettings with { QualifyNames = true };
this.functionPointerTypeSettings = this.generalTypeSettings with { QualifyNames = true, AvoidWinmdRootAlias = true, AllowMarshaling = false };
this.errorMessageTypeSettings = this.generalTypeSettings with { QualifyNames = true, Generator = null }; // Avoid risk of infinite recursion from errors in ToTypeSyntax
this.methodsAndConstantsClassName = IdentifierName(options.ClassName);
FetchTemplate("ComHelpers", this, out this.comHelperClass);
FetchTemplate("VariableLengthInlineArray`1", this, out this.variableLengthInlineArrayStruct1);
FetchTemplate("VariableLengthInlineArray`2", this, out this.variableLengthInlineArrayStruct2);
}
internal enum GeneratingElement
{
/// <summary>
/// Any other member that isn't otherwise enumerated.
/// </summary>
Other,
/// <summary>
/// A member on a COM interface that is actually being generated as an interface (as opposed to a struct for no-marshal COM).
/// </summary>
InterfaceMember,
/// <summary>
/// A member on a COM interface that is declared as a struct instead of an interface to avoid the marshaler.
/// </summary>
InterfaceAsStructMember,
/// <summary>
/// A delegate.
/// </summary>
Delegate,
/// <summary>
/// An extern, static method.
/// </summary>
ExternMethod,
/// <summary>
/// A property on a COM interface or struct.
/// </summary>
Property,
/// <summary>
/// A field on a struct.
/// </summary>
Field,
/// <summary>
/// A constant value.
/// </summary>
Constant,
/// <summary>
/// A function pointer.
/// </summary>
FunctionPointer,
/// <summary>
/// An enum value.
/// </summary>
EnumValue,
/// <summary>
/// A friendly overload.
/// </summary>
FriendlyOverload,
/// <summary>
/// A member on a helper class (e.g. a SafeHandle-derived class).
/// </summary>
HelperClassMember,
/// <summary>
/// A member of a struct that does <em>not</em> stand for a COM interface.
/// </summary>
StructMember,
}
private enum Feature
{
/// <summary>
/// Indicates that interfaces can declare static members. This requires at least .NET 7 and C# 11.
/// </summary>
InterfaceStaticMembers,
}
internal ImmutableDictionary<string, string> BannedAPIs => GetBannedAPIs(this.options);
internal SuperGenerator? SuperGenerator { get; set; }
/// <summary>
/// Gets the Windows.Win32 generator.
/// </summary>
internal Generator MainGenerator
{
get
{
if (this.IsWin32Sdk || this.SuperGenerator is null)
{
return this;
}
if (this.SuperGenerator.TryGetGenerator("Windows.Win32", out Generator? generator))
{
return generator;
}
throw new InvalidOperationException("Unable to find Windows.Win32 generator.");
}
}
internal GeneratorOptions Options => this.options;
internal string InputAssemblyName => this.MetadataIndex.MetadataName;
internal MetadataIndex MetadataIndex { get; }
internal MetadataReader Reader => this.metadataReader.Value;
internal LanguageVersion LanguageVersion => this.parseOptions?.LanguageVersion ?? LanguageVersion.CSharp9;
/// <summary>
/// Gets the default generation context to use.
/// </summary>
internal Context DefaultContext => new() { AllowMarshaling = this.options.AllowMarshaling };
private bool WideCharOnly => this.options.WideCharOnly;
private string Namespace => this.MetadataIndex.CommonNamespace;
private SyntaxKind Visibility => this.options.Public ? SyntaxKind.PublicKeyword : SyntaxKind.InternalKeyword;
private bool IsWin32Sdk => string.Equals(this.MetadataIndex.MetadataName, "Windows.Win32", StringComparison.OrdinalIgnoreCase);
private IEnumerable<MemberDeclarationSyntax> NamespaceMembers
{
get
{
IEnumerable<IGrouping<string, MemberDeclarationSyntax>> members = this.committedCode.MembersByModule;
IEnumerable<MemberDeclarationSyntax> result = Enumerable.Empty<MemberDeclarationSyntax>();
int i = 0;
foreach (IGrouping<string, MemberDeclarationSyntax> entry in members)
{
ClassDeclarationSyntax partialClass = DeclarePInvokeClass(entry.Key)
.AddMembers(entry.ToArray())
.WithLeadingTrivia(ParseLeadingTrivia(string.Format(CultureInfo.InvariantCulture, PartialPInvokeContentComment, entry.Key)));
if (i == 0)
{
partialClass = partialClass
.WithoutLeadingTrivia()
.AddAttributeLists(AttributeList().AddAttributes(GeneratedCodeAttribute))
.WithLeadingTrivia(partialClass.GetLeadingTrivia());
}
result = result.Concat(new MemberDeclarationSyntax[] { partialClass });
i++;
}
ClassDeclarationSyntax macrosPartialClass = DeclarePInvokeClass("Macros")
.AddMembers(this.committedCode.Macros.ToArray())
.WithLeadingTrivia(ParseLeadingTrivia(PartialPInvokeMacrosContentComment));
if (macrosPartialClass.Members.Count > 0)
{
result = result.Concat(new MemberDeclarationSyntax[] { macrosPartialClass });
}
ClassDeclarationSyntax DeclarePInvokeClass(string fileNameKey) => ClassDeclaration(Identifier(this.options.ClassName))
.AddModifiers(TokenWithSpace(this.Visibility), TokenWithSpace(SyntaxKind.StaticKeyword), TokenWithSpace(SyntaxKind.PartialKeyword))
.WithAdditionalAnnotations(new SyntaxAnnotation(SimpleFileNameAnnotation, $"{this.options.ClassName}.{fileNameKey}"));
result = result.Concat(this.committedCode.GeneratedTypes);
ClassDeclarationSyntax inlineArrayIndexerExtensionsClass = this.DeclareInlineArrayIndexerExtensionsClass();
if (inlineArrayIndexerExtensionsClass.Members.Count > 0)
{
result = result.Concat(new MemberDeclarationSyntax[] { inlineArrayIndexerExtensionsClass });
}
result = result.Concat(this.committedCode.ComInterfaceExtensions);
if (this.committedCode.TopLevelFields.Any())
{
result = result.Concat(new MemberDeclarationSyntax[] { this.DeclareConstantDefiningClass() });
}
return result;
}
}
private string DebuggerDisplayString => $"Generator: {this.InputAssemblyName}";
/// <summary>
/// Tests whether a string contains characters that do not belong in an API name.
/// </summary>
/// <param name="apiName">The user-supplied string that was expected to match some API name.</param>
/// <returns><see langword="true"/> if the string contains characters that are likely mistakenly included and causing a mismatch; <see langword="false"/> otherwise.</returns>
public static bool ContainsIllegalCharactersForAPIName(string apiName)
{
if (apiName is null)
{
throw new ArgumentNullException(nameof(apiName));
}
for (int i = 0; i < apiName.Length; i++)
{
char ch = apiName[i];
bool allowed = false;
allowed |= char.IsLetterOrDigit(ch);
allowed |= ch == '_';
allowed |= ch == '.'; // for qualified name searches
if (!allowed)
{
return true;
}
}
return false;
}
/// <inheritdoc/>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <inheritdoc/>
public void GenerateAll(CancellationToken cancellationToken)
{
this.GenerateAllExternMethods(cancellationToken);
// Also generate all structs/enum types too, even if not referenced by a method,
// since some methods use `void*` types and require structs at runtime.
this.GenerateAllInteropTypes(cancellationToken);
this.GenerateAllConstants(cancellationToken);
this.GenerateAllMacros(cancellationToken);
}
/// <inheritdoc/>
public bool TryGenerate(string apiNameOrModuleWildcard, out IReadOnlyCollection<string> preciseApi, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(apiNameOrModuleWildcard))
{
throw new ArgumentException("API cannot be null or empty.", nameof(apiNameOrModuleWildcard));
}
if (apiNameOrModuleWildcard.EndsWith(".*", StringComparison.Ordinal))
{
if (this.TryGenerateAllExternMethods(apiNameOrModuleWildcard.Substring(0, apiNameOrModuleWildcard.Length - 2), cancellationToken))
{
preciseApi = ImmutableList.Create(apiNameOrModuleWildcard);
return true;
}
else
{
preciseApi = ImmutableList<string>.Empty;
return false;
}
}
else if (apiNameOrModuleWildcard.EndsWith("*", StringComparison.Ordinal))
{
if (this.TryGenerateConstants(apiNameOrModuleWildcard))
{
preciseApi = ImmutableList.Create(apiNameOrModuleWildcard);
return true;
}
else
{
preciseApi = ImmutableList<string>.Empty;
return false;
}
}
else
{
bool result = this.TryGenerateNamespace(apiNameOrModuleWildcard, out preciseApi);
if (result || preciseApi.Count > 1)
{
return result;
}
result = this.TryGenerateExternMethod(apiNameOrModuleWildcard, out preciseApi);
if (result || preciseApi.Count > 1)
{
return result;
}
result = this.TryGenerateType(apiNameOrModuleWildcard, out preciseApi);
if (result || preciseApi.Count > 1)
{
return result;
}
result = this.TryGenerateConstant(apiNameOrModuleWildcard, out preciseApi);
if (result || preciseApi.Count > 1)
{
return result;
}
result = this.TryGenerateMacro(apiNameOrModuleWildcard, out preciseApi);
if (result || preciseApi.Count > 1)
{
return result;
}
return false;
}
}
/// <summary>
/// Generates all APIs within a given namespace, and their dependencies.
/// </summary>
/// <param name="namespace">The namespace to generate APIs for.</param>
/// <param name="preciseApi">Receives the canonical API names that <paramref name="namespace"/> matched on.</param>
/// <returns><see langword="true"/> if a matching namespace was found; otherwise <see langword="false"/>.</returns>
public bool TryGenerateNamespace(string @namespace, out IReadOnlyCollection<string> preciseApi)
{
if (@namespace is null)
{
throw new ArgumentNullException(nameof(@namespace));
}
NamespaceMetadata? metadata;
if (!this.MetadataIndex.MetadataByNamespace.TryGetValue(@namespace, out metadata))
{
// Fallback to case insensitive search if it looks promising to do so.
if (@namespace.StartsWith(this.MetadataIndex.CommonNamespace, StringComparison.OrdinalIgnoreCase))
{
foreach (KeyValuePair<string, NamespaceMetadata> item in this.MetadataIndex.MetadataByNamespace)
{
if (string.Equals(item.Key, @namespace, StringComparison.OrdinalIgnoreCase))
{
@namespace = item.Key;
metadata = item.Value;
break;
}
}
}
}
if (metadata is object)
{
this.volatileCode.GenerationTransaction(delegate
{
foreach (KeyValuePair<string, MethodDefinitionHandle> method in metadata.Methods)
{
this.RequestExternMethod(method.Value);
}
foreach (KeyValuePair<string, TypeDefinitionHandle> type in metadata.Types)
{
this.RequestInteropType(type.Value, this.DefaultContext);
}
foreach (KeyValuePair<string, FieldDefinitionHandle> field in metadata.Fields)
{
this.RequestConstant(field.Value);
}
});
preciseApi = ImmutableList.Create(@namespace);
return true;
}
preciseApi = ImmutableList<string>.Empty;
return false;
}
/// <inheritdoc/>
public void GenerateAllMacros(CancellationToken cancellationToken)
{
if (!this.IsWin32Sdk)
{
// We only have macros to generate for the main SDK.
return;
}
foreach (KeyValuePair<string, MethodDeclarationSyntax> macro in Win32SdkMacros)
{
cancellationToken.ThrowIfCancellationRequested();
try
{
this.volatileCode.GenerationTransaction(delegate
{
this.RequestMacro(macro.Value);
});
}
catch (GenerationFailedException ex) when (IsPlatformCompatibleException(ex))
{
// Something transitively required for this field is not available for this platform, so skip this method.
}
}
}
/// <inheritdoc/>
public void GenerateAllInteropTypes(CancellationToken cancellationToken)
{
foreach (TypeDefinitionHandle typeDefinitionHandle in this.Reader.TypeDefinitions)
{
cancellationToken.ThrowIfCancellationRequested();
TypeDefinition typeDef = this.Reader.GetTypeDefinition(typeDefinitionHandle);
if (typeDef.BaseType.IsNil && (typeDef.Attributes & TypeAttributes.Interface) != TypeAttributes.Interface)
{
continue;
}
if (this.Reader.StringComparer.Equals(typeDef.Namespace, InteropDecorationNamespace))
{
// Ignore the attributes that describe the metadata.
continue;
}
if (this.IsCompatibleWithPlatform(typeDef.GetCustomAttributes()))
{
try
{
this.volatileCode.GenerationTransaction(delegate
{
this.RequestInteropType(typeDefinitionHandle, this.DefaultContext);
});
}
catch (GenerationFailedException ex) when (IsPlatformCompatibleException(ex))
{
// Something transitively required for this type is not available for this platform, so skip this method.
}
}
}
}
/// <inheritdoc/>
public bool TryGenerateType(string possiblyQualifiedName, out IReadOnlyCollection<string> preciseApi)
{
if (possiblyQualifiedName is null)
{
throw new ArgumentNullException(nameof(possiblyQualifiedName));
}
TrySplitPossiblyQualifiedName(possiblyQualifiedName, out string? typeNamespace, out string typeName);
var matchingTypeHandles = new List<TypeDefinitionHandle>();
IEnumerable<NamespaceMetadata>? namespaces = this.GetNamespacesToSearch(typeNamespace);
bool foundApiWithMismatchedPlatform = false;
foreach (NamespaceMetadata? nsMetadata in namespaces)
{
if (nsMetadata.Types.TryGetValue(typeName, out TypeDefinitionHandle handle))
{
matchingTypeHandles.Add(handle);
}
else if (nsMetadata.TypesForOtherPlatform.Contains(typeName))
{
foundApiWithMismatchedPlatform = true;
}
}
if (matchingTypeHandles.Count == 1)
{
this.volatileCode.GenerationTransaction(delegate
{
this.RequestInteropType(matchingTypeHandles[0], this.DefaultContext);
});
TypeDefinition td = this.Reader.GetTypeDefinition(matchingTypeHandles[0]);
preciseApi = ImmutableList.Create($"{this.Reader.GetString(td.Namespace)}.{this.Reader.GetString(td.Name)}");
return true;
}
else if (matchingTypeHandles.Count > 1)
{
preciseApi = ImmutableList.CreateRange(
matchingTypeHandles.Select(h =>
{
TypeDefinition td = this.Reader.GetTypeDefinition(h);
return $"{this.Reader.GetString(td.Namespace)}.{this.Reader.GetString(td.Name)}";
}));
return false;
}
if (this.InputAssemblyName.Equals("Windows.Win32", StringComparison.OrdinalIgnoreCase) && SpecialTypeDefNames.Contains(typeName))
{
string? fullyQualifiedName = null;
this.volatileCode.GenerationTransaction(() => this.RequestSpecialTypeDefStruct(typeName, out fullyQualifiedName));
preciseApi = ImmutableList.Create(fullyQualifiedName!);
return true;
}
if (foundApiWithMismatchedPlatform)
{
throw new PlatformIncompatibleException($"The requested API ({possiblyQualifiedName}) was found but is not available given the target platform ({this.compilation?.Options.Platform}).");
}
preciseApi = ImmutableList<string>.Empty;
return false;
}
/// <summary>
/// Generate code for the named macro, if it is recognized.
/// </summary>
/// <param name="macroName">The name of the macro. Never qualified with a namespace.</param>
/// <param name="preciseApi">Receives the canonical API names that <paramref name="macroName"/> matched on.</param>
/// <returns><see langword="true"/> if a match was found and the macro generated; otherwise <see langword="false"/>.</returns>
public bool TryGenerateMacro(string macroName, out IReadOnlyCollection<string> preciseApi)
{
if (macroName is null)
{
throw new ArgumentNullException(nameof(macroName));
}
if (!this.IsWin32Sdk || !Win32SdkMacros.TryGetValue(macroName, out MethodDeclarationSyntax macro))
{
preciseApi = Array.Empty<string>();
return false;
}
this.volatileCode.GenerationTransaction(delegate
{
this.RequestMacro(macro);
});
preciseApi = ImmutableList.Create(macroName);
return true;
}
/// <inheritdoc/>
public IReadOnlyList<string> GetSuggestions(string name)
{
if (name is null)
{
throw new ArgumentNullException(nameof(name));
}
// Trim suffixes off the name.
var suffixes = new List<string> { "A", "W", "32", "64", "Ex" };
foreach (string suffix in suffixes)
{
if (name.EndsWith(suffix, StringComparison.Ordinal))
{
name = name.Substring(0, name.Length - suffix.Length);
}
}
// We should match on any API for which the given string is a substring.
List<string> suggestions = new();
foreach (NamespaceMetadata nsMetadata in this.MetadataIndex.MetadataByNamespace.Values)
{
foreach (string candidate in nsMetadata.Fields.Keys.Concat(nsMetadata.Types.Keys).Concat(nsMetadata.Methods.Keys))
{
if (candidate.Contains(name))
{
suggestions.Add(candidate);
}
}
}
return suggestions;
}
/// <inheritdoc/>
public IEnumerable<KeyValuePair<string, CompilationUnitSyntax>> GetCompilationUnits(CancellationToken cancellationToken)
{
if (this.committedCode.IsEmpty)
{
return ImmutableDictionary<string, CompilationUnitSyntax>.Empty;
}
NamespaceDeclarationSyntax? starterNamespace = NamespaceDeclaration(ParseName(this.Namespace));
// .g.cs because the resulting files are not user-created.
const string FilenamePattern = "{0}.g.cs";
Dictionary<string, CompilationUnitSyntax> results = new(StringComparer.OrdinalIgnoreCase);
IEnumerable<MemberDeclarationSyntax> GroupMembersByNamespace(IEnumerable<MemberDeclarationSyntax> members)
{
return members.GroupBy(member =>
member.HasAnnotations(NamespaceContainerAnnotation) ? member.GetAnnotations(NamespaceContainerAnnotation).Single().Data : null)
.SelectMany(nsContents =>
nsContents.Key is object
? new MemberDeclarationSyntax[] { NamespaceDeclaration(ParseName(nsContents.Key)).AddMembers(nsContents.ToArray()) }
: nsContents.ToArray());
}
if (this.options.EmitSingleFile)
{
CompilationUnitSyntax file = CompilationUnit()
.AddMembers(starterNamespace.AddMembers(GroupMembersByNamespace(this.NamespaceMembers).ToArray()))
.AddMembers(this.committedCode.GeneratedTopLevelTypes.ToArray());
results.Add(
string.Format(CultureInfo.InvariantCulture, FilenamePattern, "NativeMethods"),
file);
}
else
{
foreach (MemberDeclarationSyntax topLevelType in this.committedCode.GeneratedTopLevelTypes)
{
string typeName = topLevelType.DescendantNodesAndSelf().OfType<BaseTypeDeclarationSyntax>().First().Identifier.ValueText;
results.Add(
string.Format(CultureInfo.InvariantCulture, FilenamePattern, typeName),
CompilationUnit().AddMembers(topLevelType));
}
IEnumerable<IGrouping<string?, MemberDeclarationSyntax>>? membersByFile = this.NamespaceMembers.GroupBy(
member => member.HasAnnotations(SimpleFileNameAnnotation)
? member.GetAnnotations(SimpleFileNameAnnotation).Single().Data
: member switch
{
ClassDeclarationSyntax classDecl => classDecl.Identifier.ValueText,
StructDeclarationSyntax structDecl => structDecl.Identifier.ValueText,
InterfaceDeclarationSyntax ifaceDecl => ifaceDecl.Identifier.ValueText,
EnumDeclarationSyntax enumDecl => enumDecl.Identifier.ValueText,
DelegateDeclarationSyntax delegateDecl => "Delegates", // group all delegates in one file
_ => throw new NotSupportedException("Unsupported member type: " + member.GetType().Name),
},
StringComparer.OrdinalIgnoreCase);
foreach (IGrouping<string?, MemberDeclarationSyntax>? fileSimpleName in membersByFile)
{
try
{
CompilationUnitSyntax file = CompilationUnit()
.AddMembers(starterNamespace.AddMembers(GroupMembersByNamespace(fileSimpleName).ToArray()));
results.Add(
string.Format(CultureInfo.InvariantCulture, FilenamePattern, fileSimpleName.Key),
file);
}
catch (ArgumentException ex)
{
throw new GenerationFailedException($"Failed adding \"{fileSimpleName.Key}\".", ex);
}
}
}
var usingDirectives = new List<UsingDirectiveSyntax>
{
UsingDirective(AliasQualifiedName(IdentifierName(Token(SyntaxKind.GlobalKeyword)), IdentifierName(nameof(System)))),
UsingDirective(AliasQualifiedName(IdentifierName(Token(SyntaxKind.GlobalKeyword)), IdentifierName(nameof(System) + "." + nameof(System.Diagnostics)))),
UsingDirective(AliasQualifiedName(IdentifierName(Token(SyntaxKind.GlobalKeyword)), IdentifierName(nameof(System) + "." + nameof(System.Diagnostics) + "." + nameof(System.Diagnostics.CodeAnalysis)))),
UsingDirective(ParseName(GlobalNamespacePrefix + SystemRuntimeCompilerServices)),
UsingDirective(ParseName(GlobalNamespacePrefix + SystemRuntimeInteropServices)),
};
if (this.generateSupportedOSPlatformAttributes)
{
usingDirectives.Add(UsingDirective(ParseName(GlobalNamespacePrefix + "System.Runtime.Versioning")));
}
usingDirectives.Add(UsingDirective(NameEquals(GlobalWinmdRootNamespaceAlias), ParseName(GlobalNamespacePrefix + this.MetadataIndex.CommonNamespace)));
var normalizedResults = new Dictionary<string, CompilationUnitSyntax>(StringComparer.OrdinalIgnoreCase);
results.AsParallel().WithCancellation(cancellationToken).ForAll(kv =>
{
CompilationUnitSyntax? compilationUnit = ((CompilationUnitSyntax)kv.Value
.AddUsings(usingDirectives.ToArray())
.Accept(new WhitespaceRewriter())!)
.WithLeadingTrivia(FileHeader);
lock (normalizedResults)
{
normalizedResults.Add(kv.Key, compilationUnit);
}
});
if (this.compilation?.GetTypeByMetadataName("System.Reflection.AssemblyMetadataAttribute") is not null)
{
if (this.options.EmitSingleFile)
{
KeyValuePair<string, CompilationUnitSyntax> originalEntry = normalizedResults.Single();
normalizedResults[originalEntry.Key] = originalEntry.Value.WithLeadingTrivia().AddAttributeLists(CsWin32StampAttribute).WithLeadingTrivia(originalEntry.Value.GetLeadingTrivia());
}
else
{
normalizedResults.Add(string.Format(CultureInfo.InvariantCulture, FilenamePattern, "CsWin32Stamp"), CompilationUnit().AddAttributeLists(CsWin32StampAttribute).WithLeadingTrivia(FileHeader));
}
}
if (this.needsWinRTCustomMarshaler)
{
string? marshalerText = FetchTemplateText(WinRTCustomMarshalerClass);
if (marshalerText == null)
{
throw new GenerationFailedException($"Failed to get template for \"{WinRTCustomMarshalerClass}\".");
}
SyntaxTree? marshalerContents = SyntaxFactory.ParseSyntaxTree(marshalerText, cancellationToken: cancellationToken);
if (marshalerContents == null)
{
throw new GenerationFailedException($"Failed adding \"{WinRTCustomMarshalerClass}\".");
}
CompilationUnitSyntax? compilationUnit = ((CompilationUnitSyntax)marshalerContents.GetRoot(cancellationToken))
.WithLeadingTrivia(ParseLeadingTrivia(AutoGeneratedHeader));
normalizedResults.Add(
string.Format(CultureInfo.InvariantCulture, FilenamePattern, WinRTCustomMarshalerClass),
compilationUnit);
}
return normalizedResults;
}
internal static ImmutableDictionary<string, string> GetBannedAPIs(GeneratorOptions options) => options.AllowMarshaling ? BannedAPIsWithMarshaling : BannedAPIsWithoutMarshaling;
/// <summary>
/// Checks whether an exception was originally thrown because of a target platform incompatibility.
/// </summary>
/// <param name="ex">An exception that may be or contain a <see cref="PlatformIncompatibleException"/>.</param>
/// <returns><see langword="true"/> if <paramref name="ex"/> or an inner exception is a <see cref="PlatformIncompatibleException"/>; otherwise <see langword="false" />.</returns>
internal static bool IsPlatformCompatibleException(Exception? ex)
{
if (ex is null)
{
return false;
}
return ex is PlatformIncompatibleException || IsPlatformCompatibleException(ex?.InnerException);
}
internal static string ReplaceCommonNamespaceWithAlias(Generator? generator, string fullNamespace)
{
return generator is object && generator.TryStripCommonNamespace(fullNamespace, out string? stripped) ? (stripped.Length > 0 ? $"{GlobalWinmdRootNamespaceAlias}.{stripped}" : GlobalWinmdRootNamespaceAlias) : $"global::{fullNamespace}";
}
internal void RequestComHelpers(Context context)
{
if (this.IsWin32Sdk)
{
if (!this.IsTypeAlreadyFullyDeclared($"{this.Namespace}.{this.comHelperClass.Identifier.ValueText}"))
{
this.RequestInteropType("Windows.Win32.Foundation", "HRESULT", context);
this.volatileCode.GenerateSpecialType("ComHelpers", () => this.volatileCode.AddSpecialType("ComHelpers", this.comHelperClass));
}
if (this.IsFeatureAvailable(Feature.InterfaceStaticMembers) && !context.AllowMarshaling)
{
if (!this.IsTypeAlreadyFullyDeclared($"{this.Namespace}.{IVTableInterface.Identifier.ValueText}"))
{
this.volatileCode.GenerateSpecialType("IVTable", () => this.volatileCode.AddSpecialType("IVTable", IVTableInterface));
}
if (!this.IsTypeAlreadyFullyDeclared($"{this.Namespace}.{IVTableGenericInterface.Identifier.ValueText}`2"))
{
this.volatileCode.GenerateSpecialType("IVTable`2", () => this.volatileCode.AddSpecialType("IVTable`2", IVTableGenericInterface));
}
if (!this.TryGenerate("IUnknown", default))
{
throw new GenerationFailedException("Unable to generate IUnknown.");
}
}
}
else if (this.SuperGenerator is not null && this.SuperGenerator.TryGetGenerator("Windows.Win32", out Generator? generator))
{
generator.RequestComHelpers(context);
}
}
internal bool TryStripCommonNamespace(string fullNamespace, [NotNullWhen(true)] out string? strippedNamespace)
{
if (fullNamespace.StartsWith(this.MetadataIndex.CommonNamespaceDot, StringComparison.Ordinal))
{
strippedNamespace = fullNamespace.Substring(this.MetadataIndex.CommonNamespaceDot.Length);
return true;
}
else if (fullNamespace == this.MetadataIndex.CommonNamespace)
{
strippedNamespace = string.Empty;
return true;
}
strippedNamespace = null;
return false;
}
internal void RequestInteropType(string @namespace, string name, Context context)
{
// PERF: Skip this search if this namespace/name has already been generated (committed, or still in volatileCode).
foreach (TypeDefinitionHandle tdh in this.Reader.TypeDefinitions)
{
TypeDefinition td = this.Reader.GetTypeDefinition(tdh);
if (this.Reader.StringComparer.Equals(td.Name, name) && this.Reader.StringComparer.Equals(td.Namespace, @namespace))
{
this.volatileCode.GenerationTransaction(delegate
{
this.RequestInteropType(tdh, context);
});
return;
}
}
throw new GenerationFailedException($"Referenced type \"{@namespace}.{name}\" not found in \"{this.InputAssemblyName}\".");
}
internal void RequestInteropType(TypeDefinitionHandle typeDefHandle, Context context)
{
TypeDefinition typeDef = this.Reader.GetTypeDefinition(typeDefHandle);
if (typeDef.GetDeclaringType() is { IsNil: false } nestingParentHandle)
{
// We should only generate this type into its parent type.
this.RequestInteropType(nestingParentHandle, context);
return;
}
string ns = this.Reader.GetString(typeDef.Namespace);
if (!this.IsCompatibleWithPlatform(typeDef.GetCustomAttributes()))
{
// We've been asked for an interop type that does not apply. This happens because the metadata
// may use a TypeReferenceHandle or TypeDefinitionHandle to just one of many arch-specific definitions of this type.
// Try to find the appropriate definition for our target architecture.
string name = this.Reader.GetString(typeDef.Name);
NamespaceMetadata namespaceMetadata = this.MetadataIndex.MetadataByNamespace[ns];
if (!namespaceMetadata.Types.TryGetValue(name, out typeDefHandle) && namespaceMetadata.TypesForOtherPlatform.Contains(name))
{
throw new PlatformIncompatibleException($"Request for type ({ns}.{name}) that is not available given the target platform.");
}
}
bool hasUnmanagedName = this.HasUnmanagedSuffix(this.Reader, typeDef.Name, context.AllowMarshaling, this.IsManagedType(typeDefHandle));
this.volatileCode.GenerateType(typeDefHandle, hasUnmanagedName, delegate
{
if (this.RequestInteropTypeHelper(typeDefHandle, context) is MemberDeclarationSyntax typeDeclaration)
{
if (!this.TryStripCommonNamespace(ns, out string? shortNamespace))
{
throw new GenerationFailedException("Unexpected namespace: " + ns);
}
if (shortNamespace.Length > 0)
{
typeDeclaration = typeDeclaration.WithAdditionalAnnotations(
new SyntaxAnnotation(NamespaceContainerAnnotation, shortNamespace));
}
this.needsWinRTCustomMarshaler |= typeDeclaration.DescendantNodes().OfType<AttributeSyntax>()
.Any(a => a.Name.ToString() == "MarshalAs" && a.ToString().Contains(WinRTCustomMarshalerFullName));