-
Notifications
You must be signed in to change notification settings - Fork 113
/
MetadataSyntaxTreeCleaner.cs
1221 lines (1021 loc) · 52.8 KB
/
MetadataSyntaxTreeCleaner.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using MetadataUtils;
using System.Xml.Linq;
namespace ClangSharpSourceToWinmd
{
public static class MetadataSyntaxTreeCleaner
{
public const string ArgListVarName = "__arglist__";
public static SyntaxTree CleanSyntaxTree(SyntaxTree tree, Dictionary<string, string> remaps, Dictionary<string, Dictionary<string, string>> enumAdditions, HashSet<string> enumsMakeFlags, Dictionary<string, string> requiredNamespaces, Dictionary<string, string> staticLibs, HashSet<string> nonEmptyStructs, HashSet<string> enumMemberNames, string filePath)
{
TreeRewriter treeRewriter = new TreeRewriter(remaps, enumAdditions, enumsMakeFlags, requiredNamespaces, staticLibs, nonEmptyStructs, enumMemberNames);
var newRoot = (CSharpSyntaxNode)treeRewriter.Visit(tree.GetRoot());
var ret = CSharpSyntaxTree.Create(newRoot, null, filePath);
return ret;
}
private class TreeRewriter : CSharpSyntaxRewriter
{
private static readonly Regex ElementCountRegex = new Regex(@"(?:elementCount|byteCount)\((?:_Old_\()?([^\)]+)\)+");
private static readonly Regex IsRegex = new Regex(@"[^\w::]");
private HashSet<SyntaxNode> nodesWithMarshalAs = new HashSet<SyntaxNode>();
private Dictionary<string, string> remaps;
private Dictionary<Regex, string> regexRemaps = new Dictionary<Regex, string>();
private Dictionary<string, Dictionary<string, string>> enumAdditions;
private Dictionary<string, string> requiredNamespaces;
private Dictionary<string, string> staticLibs;
private HashSet<string> visitedDelegateNames = new HashSet<string>();
private HashSet<string> visitedStaticMethodNames = new HashSet<string>();
private HashSet<string> nonEmptyStructs;
private HashSet<string> enumMemberNames;
private HashSet<string> enumsToMakeFlags;
private HashSet<string> usingNamespaces = new HashSet<string>();
public TreeRewriter(Dictionary<string, string> remaps, Dictionary<string, Dictionary<string, string>> enumAdditions, HashSet<string> enumsToMakeFlags, Dictionary<string, string> requiredNamespaces, Dictionary<string, string> staticLibs, HashSet<string> nonEmptyStructs, HashSet<string> enumMemberNames)
{
this.remaps = remaps;
this.InitRegexRemaps();
this.enumAdditions = enumAdditions;
this.requiredNamespaces = requiredNamespaces;
this.staticLibs = staticLibs;
this.nonEmptyStructs = nonEmptyStructs;
this.enumMemberNames = enumMemberNames;
this.enumsToMakeFlags = enumsToMakeFlags;
}
private void InitRegexRemaps()
{
foreach (var pair in this.remaps)
{
if (IsRegex.IsMatch(pair.Key))
{
this.regexRemaps[new Regex(pair.Key)] = pair.Value;
}
}
}
public override SyntaxNode VisitCompilationUnit(CompilationUnitSyntax node)
{
var ret = (CompilationUnitSyntax)base.VisitCompilationUnit(node);
// Add any namespaces we might need due to remappings
var newUsings = new List<UsingDirectiveSyntax>();
foreach (var remapNamespace in this.requiredNamespaces.Values.Distinct())
{
if (!this.usingNamespaces.Contains(remapNamespace))
{
newUsings.Add(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(remapNamespace)).NormalizeWhitespace().WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed));
}
}
if (newUsings.Count != 0)
{
ret = ret.AddUsings(newUsings.ToArray());
}
return ret;
}
public override SyntaxNode VisitUsingDirective(UsingDirectiveSyntax node)
{
this.usingNamespaces.Add(node.Name.ToString());
return base.VisitUsingDirective(node);
}
private static SyntaxList<AttributeListSyntax> FixRemappedAttributes(
SyntaxList<AttributeListSyntax> existingAttrList,
List<AttributeSyntax> remappedListAttributes)
{
return FixRemappedAttributes(existingAttrList, remappedListAttributes, null);
}
private static SyntaxList<AttributeListSyntax> FixRemappedAttributes(
SyntaxList<AttributeListSyntax> existingAttrList,
List<AttributeSyntax> remappedListAttributes,
AttributeTargetSpecifierSyntax target)
{
if (remappedListAttributes == null)
{
return existingAttrList;
}
foreach (var attrNode in remappedListAttributes)
{
var attrName = attrNode.Name.ToString();
if (attrName.EndsWith(EncodeHelpers.AttributeToRemoveSuffix))
{
var attrNameToRemove = attrName.Substring(0, attrName.Length - EncodeHelpers.AttributeToRemoveSuffix.Length);
existingAttrList = SyntaxUtils.RemoveAttribute(existingAttrList, attrNameToRemove);
}
else
{
// Remove any existing attribute with the same name
existingAttrList = SyntaxUtils.RemoveAttribute(existingAttrList, attrName);
var attrListNode =
SyntaxFactory.AttributeList(
SyntaxFactory.SingletonSeparatedList<AttributeSyntax>(attrNode));
if (target != null)
{
attrListNode = attrListNode.WithTarget(target);
}
existingAttrList = existingAttrList.Add(attrListNode);
}
}
return existingAttrList;
}
public override SyntaxNode VisitParameter(ParameterSyntax node)
{
if (node.Identifier.Text == "__arglist")
{
// Special case __arglist to give it the type of "object" and a name we'll recognize in the emitter.
// Otherwise the compilation will fail if __arglist is found in any delegates
return node
.WithIdentifier(SyntaxFactory.Identifier(ArgListVarName))
.WithTrailingTrivia(SyntaxFactory.Space)
.WithType(SyntaxFactory.ParseTypeName("object")
.WithTrailingTrivia(SyntaxFactory.Space));
}
string fullName = GetFullNameWithoutArchSuffix(node);
if (this.GetRemapInfo(fullName, node.AttributeLists, out var listAttributes, node.Type.ToString(), out string newType, out string newName))
{
node = (ParameterSyntax)base.VisitParameter(node);
node = node.WithAttributeLists(FixRemappedAttributes(node.AttributeLists, listAttributes));
if (newName != null)
{
node = node.WithIdentifier(SyntaxFactory.Identifier(newName));
}
if (newType != null)
{
node = node.WithType(SyntaxFactory.ParseTypeName(newType).WithTrailingTrivia(SyntaxFactory.Space));
}
}
else
{
node = (ParameterSyntax)base.VisitParameter(node);
}
// Get rid of default parameter values
if (node.Default != null)
{
node = node.WithDefault(null);
}
return node;
}
public override SyntaxNode VisitStructDeclaration(StructDeclarationSyntax node)
{
// If the struct is empty and we found a non-empty struct in all the source files, delete it
if (SyntaxUtils.IsEmptyStruct(node) && this.nonEmptyStructs.Contains(node.Identifier.ValueText))
{
return null;
}
string fullName = GetFullNameWithoutArchSuffix(node);
if (this.GetRemapInfo(fullName, node.AttributeLists, out var listAttributes, null, out _, out string newName))
{
node = (StructDeclarationSyntax)base.VisitStructDeclaration(node);
node = node.WithAttributeLists(FixRemappedAttributes(node.AttributeLists, listAttributes));
if (newName != null)
{
node = node.WithIdentifier(SyntaxFactory.Identifier(newName));
}
}
else
{
node = (StructDeclarationSyntax)base.VisitStructDeclaration(node);
}
foreach (var member in node.Members)
{
if (!(member is FieldDeclarationSyntax))
{
continue;
}
var fieldName = ((FieldDeclarationSyntax)member).Declaration.Variables[0].Identifier.Value.ToString();
if (fieldName == "cbSize")
{
var attributeList = SyntaxFactory.AttributeList(
SyntaxFactory.SingletonSeparatedList<AttributeSyntax>(
SyntaxFactory.Attribute(
SyntaxFactory.ParseName("StructSizeField"),
SyntaxFactory.ParseAttributeArgumentList($"(\"{fieldName}\")"))));
node = node.AddAttributeLists(attributeList);
}
}
return node;
}
public override SyntaxNode VisitFieldDeclaration(FieldDeclarationSyntax node)
{
const string ForceConstPrefix = "__forceconst__";
string localName = node.Declaration.Variables.First().Identifier.ValueText;
// If it's a constant, ignore it if it's already part of an enum
if (node.Modifiers.ToString() == "public const")
{
if (this.enumMemberNames.Contains(localName))
{
return null;
}
}
string fullName = GetFullNameWithoutArchSuffix(node);
this.GetRemapInfo(fullName, node.AttributeLists, out var listAttributes, node.Declaration.Type.ToString(), out string newType, out string newName);
// ClangSharp mistakenly emits string[] for WCHAR[] Foo = "Bar".
// Change it to string
if (newType == null && node.Declaration.Type.ToString() == "string[]")
{
newType = "string";
}
// We will turn static strings into constants
if (node.Modifiers.ToString() == "public static" && node.Declaration.Type.ToString() == "string")
{
var newModifiers =
SyntaxFactory.TokenList(
SyntaxFactory.Token(SyntaxKind.PublicKeyword).WithTrailingTrivia(SyntaxFactory.Space),
SyntaxFactory.Token(SyntaxKind.ConstKeyword).WithTrailingTrivia(SyntaxFactory.Space));
node = node.WithModifiers(newModifiers).WithLeadingTrivia(node.GetLeadingTrivia());
return node;
}
if (node.Modifiers.ToString() == "public static readonly")
{
// Turn public static readonly Guids into string constants with an attribute
// to signal language projections to turn them into Guid constants. Guid constants
// aren't allowed in metadata, requiring us to surface them this way
if (node.Declaration.Type.ToString() == "Guid")
{
var varInitializer = node.Declaration.Variables.First().Initializer;
if (varInitializer.Value is ObjectCreationExpressionSyntax objCreationSyntax)
{
node = node.RemoveNode(varInitializer, SyntaxRemoveOptions.KeepExteriorTrivia | SyntaxRemoveOptions.KeepEndOfLine);
var args = objCreationSyntax.ArgumentList.Arguments;
if (args.Count == 11)
{
var allArgs = $"(uint){args}";
string argsFormatted = $"({allArgs})";
var attrsList =
SyntaxFactory.AttributeList(
SyntaxFactory.SingletonSeparatedList<AttributeSyntax>(
SyntaxFactory.Attribute(
SyntaxFactory.ParseName("Windows.Win32.Interop.Guid"),
SyntaxFactory.ParseAttributeArgumentList(argsFormatted))));
node = node.AddAttributeLists(attrsList).WithLeadingTrivia(node.GetLeadingTrivia());
}
else if (objCreationSyntax.ArgumentList.Arguments.Count == 1)
{
var textValue = EncodeHelpers.RemoveQuotes(objCreationSyntax.ArgumentList.Arguments[0].ToString());
// If this is an invalid format, remove the node
if (!Guid.TryParse(textValue, out var guidVal))
{
return null;
}
node = node.AddAttributeLists(EncodeHelpers.ConvertGuidToAttributeList(guidVal).WithLeadingTrivia(node.GetLeadingTrivia()));
}
}
return node;
}
// Some constants get scraped as public static readonly.
// If we see the prefix, force it to be a const
else if (localName.StartsWith(ForceConstPrefix))
{
var newModifiers =
SyntaxFactory.TokenList(
SyntaxFactory.Token(SyntaxKind.PublicKeyword).WithTrailingTrivia(SyntaxFactory.Space),
SyntaxFactory.Token(SyntaxKind.ConstKeyword).WithTrailingTrivia(SyntaxFactory.Space));
node = node.WithModifiers(newModifiers).WithLeadingTrivia(node.GetLeadingTrivia());
var variable = node.Declaration.Variables.First();
variable = variable.WithIdentifier(SyntaxFactory.ParseToken(localName.Substring(ForceConstPrefix.Length)));
node = node.WithDeclaration(node.Declaration.WithVariables(SyntaxFactory.SingletonSeparatedList(variable)));
return node;
}
}
node = (FieldDeclarationSyntax)base.VisitFieldDeclaration(node);
node = node.WithAttributeLists(FixRemappedAttributes(node.AttributeLists, listAttributes));
var firstVar = node.Declaration.Variables.First();
if (newName != null)
{
var newVar = SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(newName));
node = node.ReplaceNode(firstVar, newVar);
}
if (newType != null)
{
node = node.WithDeclaration(node.Declaration.WithType(SyntaxFactory.ParseTypeName(newType).WithTrailingTrivia(SyntaxFactory.Space)));
}
return node;
}
public override SyntaxNode VisitAttributeList(AttributeListSyntax node)
{
var firstAttr = node.Attributes[0];
var attrName = firstAttr.Name.ToString();
switch (attrName)
{
// We don't want more than one of these on an interface. Get rid of it if the
// struct doesn't have a NativeTypeName, which means it's a forward declaration.
// The real declaration will have the SupportedOSPlatform that we'll keep
case "SupportedOSPlatform":
{
if (node.Parent is StructDeclarationSyntax structDeclaration)
{
if (!structDeclaration.AttributeLists.Any(list => list.Attributes.Any(attr => attr.Name.ToString() == "NativeTypeName")))
{
return null;
}
}
// We don't want these for parameters or fields
if (node.Parent is ParameterSyntax || node.Parent is FieldDeclarationSyntax)
{
return null;
}
// We don't want these for interface methods
if (node.Parent is MethodDeclarationSyntax && node.Parent.Parent is StructDeclarationSyntax)
{
return null;
}
break;
}
case "Guid":
{
return this.ProcessGuidAttr(firstAttr);
}
case "UnmanagedFunctionPointer":
{
// ClangSharp can emit this attribute with no arguments.
// The typedef we're using of this attribute has no such ctor,
// so emit one that does, using WinApi as the default calling convention.
// Also, convert StdCall to Winapi
if (firstAttr.ArgumentList == null || firstAttr.ArgumentList.ToString() == "(CallingConvention.StdCall)")
{
return
SyntaxFactory.AttributeList(
SyntaxFactory.SingletonSeparatedList<AttributeSyntax>(
SyntaxFactory.Attribute(
SyntaxFactory.ParseName("UnmanagedFunctionPointer"),
SyntaxFactory.ParseAttributeArgumentList("(CallingConvention.Winapi)"))));
}
break;
}
case "NativeTypeName":
{
bool alreadyConst =
node.Parent is FieldDeclarationSyntax parentField &&
parentField.Modifiers.Any(m => m.ToString() == "const");
var ret = this.ProcessNativeTypeNameAttr(alreadyConst, firstAttr);
return ret == null ? node : ret;
}
case "CppAttributeList":
{
return this.CreateAttributeListForSal(node);
}
}
return base.VisitAttributeList(node);
}
public override SyntaxNode VisitEnumDeclaration(EnumDeclarationSyntax node)
{
node = (EnumDeclarationSyntax)base.VisitEnumDeclaration(node);
var enumName = node.Identifier.ValueText;
if (this.GetRemapInfo(enumName, node.AttributeLists, out var listAttributes, null, out _, out _))
{
node = node.WithAttributeLists(FixRemappedAttributes(node.AttributeLists, listAttributes));
}
if (this.enumAdditions.TryGetValue(enumName, out var additionsList))
{
List<EnumMemberDeclarationSyntax> newMembers = new List<EnumMemberDeclarationSyntax>();
foreach (var additionPair in additionsList)
{
var member =
SyntaxFactory.EnumMemberDeclaration(additionPair.Key)
.WithEqualsValue(
SyntaxFactory.EqualsValueClause(
SyntaxFactory.ParseExpression(additionPair.Value)));
newMembers.Add(member);
}
node = node.AddMembers(newMembers.ToArray());
}
if (this.enumsToMakeFlags.Contains(enumName))
{
bool hasFlags = SyntaxUtils.GetAttribute(node.AttributeLists, "Flags") != null;
if (!hasFlags)
{
node =
node.AddAttributeLists(
SyntaxFactory.AttributeList(
SyntaxFactory.SingletonSeparatedList<AttributeSyntax>(
SyntaxFactory.Attribute(SyntaxFactory.ParseName("global::System.Flags")))).WithLeadingTrivia(node.GetLeadingTrivia()));
}
}
return node;
}
public override SyntaxNode VisitDelegateDeclaration(DelegateDeclarationSyntax node)
{
string fullName = SyntaxUtils.GetFullName(node);
// Remove duplicate delegates in this tree
if (this.visitedDelegateNames.Contains(fullName))
{
return null;
}
this.visitedDelegateNames.Add(fullName);
string fixedName = GetFullNameWithoutArchSuffix(node);
string returnFullName = $"{fixedName}::return";
if (this.GetRemapInfo(returnFullName, node.AttributeLists, out var listAttributes, node.ReturnType.ToString(), out var newType, out _))
{
node = (DelegateDeclarationSyntax)base.VisitDelegateDeclaration(node);
var target = SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Token(SyntaxKind.ReturnKeyword));
node = node.WithAttributeLists(FixRemappedAttributes(node.AttributeLists, listAttributes, target));
if (newType != null)
{
node = node.WithReturnType(SyntaxFactory.ParseTypeName(newType).WithTrailingTrivia(SyntaxFactory.Space));
}
return node;
}
return base.VisitDelegateDeclaration(node);
}
public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node)
{
var dllImportAttr = SyntaxUtils.GetAttribute(node.AttributeLists, "DllImport");
string dllName = dllImportAttr?.ArgumentList.Arguments[0].ToString();
// Trim the leading and trailing quotes.
dllName = dllName?.Substring(1, dllName.Length - 2);
// Skip methods where we weren't given an import lib name. Should we warn the caller?
if (dllImportAttr != null && string.IsNullOrEmpty(dllName))
{
return null;
}
string fullName = SyntaxUtils.GetFullName(node);
string fixedFullName = GetFullNameWithoutArchSuffix(node);
// Remove duplicate static methods
if (node.Body == null)
{
// If this function is supposed to be in a certain namespace, remove it if it's not.
// We only respect this for static methods
if (this.requiredNamespaces.TryGetValue(fixedFullName, out var requiredNamespace))
{
var ns = GetEnclosingNamespace(node);
if (ns != requiredNamespace)
{
return null;
}
}
// Remove duplicate methods in this tree
if (this.visitedStaticMethodNames.Contains(fullName))
{
return null;
}
this.visitedStaticMethodNames.Add(fullName);
}
// Any method with a body has to be part of a call to a vtable for an interface.
// If it's not, get rid of it
else if (!node.Body.ToString().Contains("GetDelegateForFunctionPointer"))
{
return null;
}
string returnFullName = $"{fixedFullName}::return";
string nodeReturnType = node.ReturnType.ToString();
node = (MethodDeclarationSyntax)base.VisitMethodDeclaration(node);
// Add the StaticLibrary attribute if one was specified for this DLL.
if (!string.IsNullOrEmpty(dllName) && this.staticLibs.TryGetValue(dllName, out string staticLib))
{
var attrListNode = SyntaxFactory.AttributeList(
SyntaxFactory.SingletonSeparatedList<AttributeSyntax>(
SyntaxFactory.Attribute(SyntaxFactory.ParseName("StaticLibrary"),
SyntaxFactory.ParseAttributeArgumentList($"(\"{staticLib}\")"))));
node = node.WithAttributeLists(node.AttributeLists.Add(attrListNode));
}
// See if there are any attributes directly on the method
if (this.GetRemapInfo(fullName, node.AttributeLists, out var methodAttributes, null, out _, out _))
{
node = node.WithAttributeLists(FixRemappedAttributes(node.AttributeLists, methodAttributes));
}
// Find remap info for the return parameter for this method and apply any that we find
if (this.GetRemapInfo(returnFullName, node.AttributeLists, out var listAttributes, nodeReturnType, out var newType, out _))
{
var target = SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Token(SyntaxKind.ReturnKeyword));
node = node.WithAttributeLists(FixRemappedAttributes(node.AttributeLists, listAttributes, target));
if (newType != null)
{
node = node.WithReturnType(SyntaxFactory.ParseTypeName(newType).WithTrailingTrivia(SyntaxFactory.Space));
}
}
return node;
}
private static string GetEnclosingNamespace(SyntaxNode node)
{
for (SyntaxNode currentNode = node; node != null; node = node.Parent)
{
if (node is NamespaceDeclarationSyntax nsNode)
{
return nsNode.Name.ToString();
}
}
return null;
}
private static string GetFullNameWithoutArchSuffix(SyntaxNode node)
{
string ret = SyntaxUtils.GetFullName(node);
ret = ret.Replace("____1", string.Empty);
ret = ret.Replace("____2", string.Empty);
return ret;
}
private string GetInfoForNativeType(string nativeTypeName, out bool isConst, out bool isNullTerminated, out bool isNullNullTerminated)
{
string metadataType = null;
isConst = false;
isNullTerminated = false;
isNullNullTerminated = false;
if (this.remaps.TryGetValue(nativeTypeName, out var attrs))
{
if (attrs.Contains("[Const]"))
{
isConst = true;
}
}
switch (nativeTypeName)
{
case "LPCGUID":
case "LPCVOID":
isConst = true;
break;
case "PCHAR":
case "LPCH":
case "PCH":
metadataType = ClangSharpSourceWinmdGenerator.Win32StringType;
break;
case "LPCCH":
case "PCCH":
metadataType = ClangSharpSourceWinmdGenerator.Win32StringType;
isConst = true;
break;
case "NPSTR":
case "LPSTR":
case "PSTR":
metadataType = ClangSharpSourceWinmdGenerator.Win32StringType;
isNullTerminated = true;
break;
case "LPCSTR":
case "PCSTR":
metadataType = ClangSharpSourceWinmdGenerator.Win32StringType;
isConst = true;
isNullTerminated = true;
break;
case "PZZSTR":
metadataType = ClangSharpSourceWinmdGenerator.Win32StringType;
isNullNullTerminated = true;
break;
case "CPZZSTR":
metadataType = ClangSharpSourceWinmdGenerator.Win32StringType;
isConst = true;
isNullNullTerminated = true;
break;
case "PWCHAR":
case "LPWCH":
case "PWCH":
metadataType = ClangSharpSourceWinmdGenerator.Win32StringType;
break;
case "NWPSTR":
case "LPWSTR":
case "PWSTR":
case "LPOLESTR":
case "PNZWCH":
case "WCHAR *":
case "OLECHAR *":
case "wchar_t *":
metadataType = ClangSharpSourceWinmdGenerator.Win32WideStringType;
isNullTerminated = true;
break;
case "LPCWSTR":
case "PCWSTR":
case "LPCWCH":
case "PCNZWCH":
case "LPCOLESTR":
case "const OLECHAR *":
case "const WCHAR *":
case "const wchar_t *":
metadataType = ClangSharpSourceWinmdGenerator.Win32WideStringType;
isNullTerminated = true;
isConst = true;
break;
case "PZZWSTR":
metadataType = ClangSharpSourceWinmdGenerator.Win32WideStringType;
isNullNullTerminated = true;
break;
case "PCZZWSTR":
metadataType = ClangSharpSourceWinmdGenerator.Win32WideStringType;
isConst = true;
isNullNullTerminated = true;
break;
default:
if (nativeTypeName.StartsWith("const ") || Regex.IsMatch(nativeTypeName, "^L?PCW?STR"))
{
isConst = true;
}
break;
}
return metadataType;
}
private void AddNativeArrayInfoAttribute(bool alreadyConst, string nativeTypeName, List<AttributeSyntax> attrsList)
{
if (string.IsNullOrWhiteSpace(nativeTypeName))
{
return;
}
var metadataType = this.GetInfoForNativeType(nativeTypeName, out bool isConst, out bool isNullTerminated, out bool isNullNullTerminated);
if (isConst && !alreadyConst)
{
attrsList.Add(SyntaxFactory.Attribute(SyntaxFactory.ParseName("Const")));
}
if (metadataType == ClangSharpSourceWinmdGenerator.Win32StringType || metadataType == ClangSharpSourceWinmdGenerator.Win32WideStringType)
{
if (!isNullTerminated)
{
attrsList.Add(SyntaxFactory.Attribute(SyntaxFactory.ParseName("NotNullTerminated")));
}
if (isNullNullTerminated)
{
attrsList.Add(SyntaxFactory.Attribute(SyntaxFactory.ParseName("NullNullTerminated")));
}
}
}
private SyntaxNode ProcessGuidAttr(AttributeSyntax guidAttr)
{
string guidStr = guidAttr.ArgumentList.Arguments[0].ToString();
guidStr = EncodeHelpers.RemoveQuotes(guidStr);
Guid guid = Guid.Parse(guidStr);
return EncodeHelpers.ConvertGuidToAttributeList(guid);
}
private SyntaxNode ProcessNativeTypeNameAttr(bool alreadyConst, AttributeSyntax nativeTypeNameAttr)
{
string nativeType = nativeTypeNameAttr.ArgumentList.Arguments[0].ToString();
nativeType = EncodeHelpers.RemoveQuotes(nativeType);
List<AttributeSyntax> attributeNodes = new List<AttributeSyntax>();
this.AddNativeArrayInfoAttribute(alreadyConst, nativeType, attributeNodes);
attributeNodes.Insert(0, nativeTypeNameAttr);
var ret = SyntaxFactory.AttributeList(SyntaxFactory.SeparatedList(attributeNodes));
if (((AttributeListSyntax)nativeTypeNameAttr.Parent).Target is AttributeTargetSpecifierSyntax target
&& target.Identifier.ValueText == "return")
{
ret =
ret.WithTarget(
SyntaxFactory.AttributeTargetSpecifier(
SyntaxFactory.Token(SyntaxKind.ReturnKeyword)));
}
return ret;
}
private SyntaxNode CreateAttributeListForSal(AttributeListSyntax cppAttrList)
{
ParameterSyntax paramNode = (ParameterSyntax)cppAttrList.Parent;
bool marshalAsAdded = this.nodesWithMarshalAs.Contains(paramNode);
AttributeSyntax cppAttr = cppAttrList.Attributes[0];
List<AttributeSyntax> attributesList = new List<AttributeSyntax>();
string salText = cppAttr.ArgumentList.Arguments[0].ToString();
salText = salText.Substring(1, salText.Length - 2);
string nativeArrayInfoParams = null;
bool isIn = false;
bool isOut = false;
bool isOpt = false;
bool isReserved = false;
bool isComOutPtr = false;
bool isRetVal = false;
bool isNullNullTerminated;
bool? pre = null;
bool? post = null;
var salAttrs = GetSalAttributes(salText);
isNullNullTerminated = salAttrs.Any(a => a.Name == "SAL_name" && a.P1 == "_NullNull_terminated_");
foreach (var salAttr in salAttrs)
{
if (salAttr.Name == "SAL_name")
{
if (salAttr.P1.StartsWith("__RPC__"))
{
// TODO: Handle ecount, xcount and others that deal with counts
bool deref = false;
string[] parts = salAttr.P1.Split('_');
foreach (var part in parts)
{
switch (part)
{
case "deref":
deref = true;
break;
case "in":
isIn = true;
break;
case "out":
isOut = true;
break;
case "inout":
isIn = isOut = true;
break;
case "opt":
// As per rpcsal.h, deref_opt means input optional but deref_***_opt doesn't
if (deref && (isIn || isOut))
{
continue;
}
isOpt = true;
break;
}
}
break;
}
else if (salAttr.P1 == "_Maybenull_" || salAttr.P1 == "_Pre_maybenull_" || salAttr.P1 == "_Pre_null_")
{
isIn = true;
isOpt = true;
continue;
}
if (salAttr.P1.Contains("_opt"))
{
isOpt = true;
}
if (salAttr.P1.StartsWith("_COM_Outptr"))
{
isComOutPtr = true;
continue;
}
else if (salAttr.P1.StartsWith("_Outptr_") && !isComOutPtr)
{
isOut = true;
continue;
}
else if (salAttr.P1 == "_Reserved_")
{
isReserved = true;
continue;
}
}
if (salAttr.Name == "SAL_retval")
{
isRetVal = true;
continue;
}
if (salAttr.Name == "SAL_pre")
{
pre = true;
continue;
}
if (salAttr.Name == "SAL_post")
{
pre = false;
post = true;
continue;
}
if (salAttr.Name == "SAL_end")
{
pre = post = false;
}
if (salAttr.Name == "SAL_valid")
{
if (pre.HasValue && pre.Value)
{
isIn = true;
}
else if (post.HasValue && post.Value)
{
isOut = true;
}
else
{
isIn = isOut = true;
}
continue;
}
if (!marshalAsAdded && (salAttr.Name == "SAL_writableTo" || salAttr.Name == "SAL_readableTo") && pre.HasValue && pre.Value)
{
nativeArrayInfoParams = GetArrayMarshalAsFromP1(paramNode, salAttr.P1);
if (!string.IsNullOrEmpty(nativeArrayInfoParams))
{
marshalAsAdded = true;
}
continue;
}
}
// If we didn't add marshal as yet, try again without using pre
if (!marshalAsAdded)
{
var salAttr = salAttrs.FirstOrDefault(attr => attr.Name == "SAL_readableTo" || attr.Name == "SAL_writeableTo");
if (salAttr != null)
{
nativeArrayInfoParams = GetArrayMarshalAsFromP1(paramNode, salAttr.P1);
if (!string.IsNullOrEmpty(nativeArrayInfoParams))
{
marshalAsAdded = true;
}
}
}
if (!string.IsNullOrEmpty(nativeArrayInfoParams))
{
var attrName = SyntaxFactory.ParseName(nativeArrayInfoParams.Contains("BytesParamIndex") ? "MemorySize" : "NativeArrayInfo");
var args = SyntaxFactory.ParseAttributeArgumentList(nativeArrayInfoParams.ToString());
var finalAttr = SyntaxFactory.Attribute(attrName, args);
attributesList.Add(finalAttr);
}
if (isIn)
{
attributesList.Add(SyntaxFactory.Attribute(SyntaxFactory.ParseName("In")));
}
if (isComOutPtr)
{
attributesList.Add(SyntaxFactory.Attribute(SyntaxFactory.ParseName("ComOutPtr")));
}
else if (isOut)
{
attributesList.Add(SyntaxFactory.Attribute(SyntaxFactory.ParseName("Out")));
}
if (isReserved)
{
attributesList.Add(SyntaxFactory.Attribute(SyntaxFactory.ParseName("Reserved")));
}
if (isOpt || isReserved)
{
attributesList.Add(SyntaxFactory.Attribute(SyntaxFactory.ParseName("Optional")));
}
if (isNullNullTerminated)
{
attributesList.Add(SyntaxFactory.Attribute(SyntaxFactory.ParseName("NullNullTerminated")));
}
if (isRetVal)
{
attributesList.Add(SyntaxFactory.Attribute(SyntaxFactory.ParseName("RetVal")));
}
if (attributesList.Count == 0)
{
return null;
}