This repository was archived by the owner on Dec 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathNewClassCompiler.cs
6042 lines (5103 loc) · 278 KB
/
NewClassCompiler.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.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using Dynamo;
using Dynamo.CSLang;
using SwiftReflector.Demangling;
using SwiftReflector.ExceptionTools;
using SwiftReflector.Inventory;
using SwiftReflector.IOUtils;
using SwiftReflector.SwiftXmlReflection;
using SwiftReflector.TypeMapping;
using SwiftRuntimeLibrary;
using SwiftRuntimeLibrary.SwiftMarshal;
using Xamarin;
using SwiftReflector.Importing;
using ObjCRuntime;
namespace SwiftReflector {
public class WrappingResult {
public WrappingResult (string modulePath, string moduleLibPath,
ModuleContents inventory, ModuleDeclaration declaration, FunctionReferenceCodeMap functionReferenceCodeMap)
{
ModulePath = SwiftRuntimeLibrary.Exceptions.ThrowOnNull (modulePath, nameof(modulePath));
ModuleLibPath = SwiftRuntimeLibrary.Exceptions.ThrowOnNull (moduleLibPath, nameof(moduleLibPath));
Contents = SwiftRuntimeLibrary.Exceptions.ThrowOnNull (inventory, nameof(inventory));
Module = SwiftRuntimeLibrary.Exceptions.ThrowOnNull (declaration, nameof(declaration));
FunctionReferenceCodeMap = SwiftRuntimeLibrary.Exceptions.ThrowOnNull (functionReferenceCodeMap, nameof (functionReferenceCodeMap));
}
public string ModulePath { get; set; }
public string ModuleLibPath { get; set; }
public ModuleContents Contents { get; set; }
public ModuleDeclaration Module { get; set; }
public FunctionReferenceCodeMap FunctionReferenceCodeMap { get; set; }
static WrappingResult emptyResult = null;
public static WrappingResult Empty {
get {
if (emptyResult == null) {
emptyResult = new WrappingResult ("", "", new ModuleContents (new SwiftName ("", false), 0), new ModuleDeclaration (), new FunctionReferenceCodeMap ());
}
return emptyResult;
}
}
public bool IsEmpty {
get {
return this == emptyResult ||
(String.IsNullOrEmpty (ModulePath) && String.IsNullOrEmpty (ModuleLibPath) &&
String.IsNullOrEmpty (Contents.Name.Name));
}
}
}
public class ClassCompilerNames
{
public string ModuleName { get; }
public string WrappingModuleName { get; }
public string PinvokeClassPrefix { get; }
public string GlobalFunctionClassName { get; }
public ClassCompilerNames (string moduleName, string wrappingModuleName, string pinvokeClassPrefix = "NativeMethodsFor", string globalFunctionClassName = "TopLevelEntities")
{
ModuleName = moduleName;
WrappingModuleName = wrappingModuleName;
PinvokeClassPrefix = pinvokeClassPrefix;
GlobalFunctionClassName = globalFunctionClassName;
}
}
public class ClassCompilerLocations
{
public List<string> ModuleDirectories { get; }
public List<string> LibraryDirectories { get; }
public List<string> TypeDatabasePaths { get; }
public string XamGluePath { get; }
public ClassCompilerLocations (List<string> moduleDirectories, List<string> libraryDirectories, List<string> typeDatabasePaths, string xamGluePath = null)
{
ModuleDirectories = moduleDirectories;
LibraryDirectories = libraryDirectories;
TypeDatabasePaths = typeDatabasePaths;
XamGluePath = xamGluePath;
}
}
public class ClassCompilerOptions
{
public bool TargetPlatformIs64Bit { get; }
public bool Verbose { get; }
public bool RetainReflectedXmlOutput { get; }
public bool RetainSwiftWrappers { get; }
public UniformTargetRepresentation TargetRepresentation { get; }
public ClassCompilerOptions (bool targetPlatformIs64Bit, bool verbose, bool retainReflectedXmlOutput, bool retainSwiftWrappers,
UniformTargetRepresentation targetRepresentation)
{
TargetPlatformIs64Bit = targetPlatformIs64Bit;
Verbose = verbose;
RetainReflectedXmlOutput = retainReflectedXmlOutput;
RetainSwiftWrappers = retainSwiftWrappers;
TargetRepresentation = targetRepresentation;
}
}
public class NewClassCompiler {
public static string kISwiftObjectName = "ISwiftObject";
public static CSIdentifier kISwiftObject = new CSIdentifier (kISwiftObjectName);
public static string kSwiftNativeObjectName = "SwiftNativeObject";
public static CSIdentifier kSwiftNativeObject = new CSIdentifier (kSwiftNativeObjectName);
public static string kSwiftObjectGetterName = "SwiftObject";
public static CSIdentifier kSwiftObjectGetter = new CSIdentifier (kSwiftObjectGetterName);
public static string kObjcHandleGetterName = "Handle";
public static CSIdentifier kObjcHandleGetter = new CSIdentifier (kObjcHandleGetterName);
static string kThisName = "this";
public static string kInterfaceImplName = "xamarinImpl";
public static CSIdentifier kInterfaceImpl = new CSIdentifier (kInterfaceImplName);
public static string kContainerName = "xamarinContainer";
public static CSIdentifier kContainer = new CSIdentifier (kContainerName);
public static string kProxyExistentialContainerName = "ProxyExistentialContainer";
public static CSIdentifier kProxyExistentialContainer = new CSIdentifier (kProxyExistentialContainerName);
public static string kProtocolWitnessTableName = "ProtocolWitnessTable";
public static CSIdentifier kProtocolWitnessTable = new CSIdentifier (kProtocolWitnessTableName);
public static string kGenericSelfName = "TSelf";
public static CSIdentifier kGenericSelf = new CSIdentifier (kGenericSelfName);
public static CSIdentifier kMobilePlatforms = new CSIdentifier ("__IOS__ || __MACOS__ || __TVOS__ || __WATCHOS__");
SwiftCompilerLocation SwiftCompilerLocations;
SwiftCompilerLocation ReflectorLocations;
ClassCompilerLocations ClassCompilerLocations;
ClassCompilerNames CompilerNames;
ClassCompilerOptions Options;
UnicodeMapper UnicodeMapper;
bool Verbose => Options.Verbose;
Version CompilerVersion;
PlatformName CurrentPlatform;
bool OutputIsFramework;
TypeMapper TypeMapper;
TopLevelFunctionCompiler TLFCompiler;
public NewClassCompiler (SwiftCompilerLocation swiftCompilerLocations, ClassCompilerOptions options, UnicodeMapper unicodeMapper)
{
ReflectorLocations = SwiftRuntimeLibrary.Exceptions.ThrowOnNull (swiftCompilerLocations, nameof (swiftCompilerLocations));
SwiftCompilerLocations = new SwiftCompilerLocation ("/usr/bin", "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift-5.0/macosx");
Options = SwiftRuntimeLibrary.Exceptions.ThrowOnNull (options, nameof (options));
UnicodeMapper = unicodeMapper;
CompilerVersion = GetCompilerVersion ();
if (CompilerVersion == null)
throw ErrorHelper.CreateError (ReflectorError.kCantHappenBase + 13, "Unable to determine the version of the supplied Swift compiler.");
}
// "This is probably the best button to push."
public ErrorHandling CompileToCSharp (
ClassCompilerLocations classCompilerLocations,
ClassCompilerNames compilerNames,
CompilationTargetCollection targets,
string outputDirectory,
string minimumOSVersion = null,
string dylibXmlPath = null)
{
ClassCompilerLocations = SwiftRuntimeLibrary.Exceptions.ThrowOnNull (classCompilerLocations, nameof (classCompilerLocations));
CompilerNames = SwiftRuntimeLibrary.Exceptions.ThrowOnNull (compilerNames, nameof (compilerNames));
var isLibrary = !string.IsNullOrEmpty (dylibXmlPath);
var errors = new ErrorHandling ();
CurrentPlatform = targets.OperatingSystem;
TypeMapper = new TypeMapper (classCompilerLocations.TypeDatabasePaths, UnicodeMapper);
BindingImporter.ImportAndMerge (CurrentPlatform, TypeMapper.TypeDatabase, errors);
if (errors.AnyErrors)
return errors;
TLFCompiler = new TopLevelFunctionCompiler (TypeMapper);
var moduleNames = new List<string> { CompilerNames.ModuleName };
if (Verbose)
Console.WriteLine ("Aggregating swift types");
OutputIsFramework = UniformTargetRepresentation.ModuleIsFramework (CompilerNames.ModuleName, ClassCompilerLocations.LibraryDirectories);
var moduleInventory = GetModuleInventories (ClassCompilerLocations.LibraryDirectories, moduleNames, errors);
// Dylibs may create extra errors when Getting Module Inventories that we will ignore
if (isLibrary)
errors = new ErrorHandling ();
if (errors.AnyErrors)
return errors;
var moduleDeclarations = GetModuleDeclarations (ClassCompilerLocations.ModuleDirectories, moduleNames, outputDirectory,
Options.RetainReflectedXmlOutput, targets, errors, dylibXmlPath);
if (errors.AnyErrors)
return errors;
var declsPerModule = new List<List<BaseDeclaration>> ();
foreach (ModuleDeclaration moduleDeclaration in moduleDeclarations) {
TypeMapper.TypeDatabase.ModuleDatabaseForModuleName (moduleDeclaration.Name);
var allTypesAndTopLevel = moduleDeclaration.AllTypesAndTopLevelDeclarations;
TypeMapper.RegisterClasses (allTypesAndTopLevel.OfType<TypeDeclaration> ());
declsPerModule.Add (allTypesAndTopLevel);
foreach (var op in moduleDeclaration.Operators) {
TypeMapper.TypeDatabase.AddOperator (op, moduleDeclaration.Name);
}
}
if (errors.AnyErrors)
return errors;
if (Verbose)
Console.WriteLine ("Wrapping swift types");
try {
var result = WrapModuleContents (
moduleDeclarations,
moduleInventory,
ClassCompilerLocations.LibraryDirectories,
ClassCompilerLocations.ModuleDirectories,
moduleNames,
outputDirectory,
targets,
CompilerNames.WrappingModuleName,
Options.RetainSwiftWrappers,
errors, Verbose, OutputIsFramework, minimumOSVersion, isLibrary);
if (result == null) {
var ex = ErrorHelper.CreateError (ReflectorError.kWrappingBase, $"Failed to wrap module{(moduleNames.Count > 1 ? "s" : "")} {moduleNames.InterleaveCommas ()}.");
errors.Add (ex);
return errors;
}
CompileModules (moduleDeclarations, moduleInventory, ClassCompilerLocations.LibraryDirectories, outputDirectory, result, errors);
} catch (Exception err) {
errors.Add (err);
}
return errors;
}
void CompileModules (List<ModuleDeclaration> moduleDeclarations, ModuleInventory moduleInventory,
List<string> swiftLibPaths, string outputDirectory,
WrappingResult wrapper, ErrorHandling errors)
{
foreach (ModuleDeclaration module in moduleDeclarations) {
string swiftLibPath = FindFileForModule (module.Name, swiftLibPaths);
CompileModuleContents (module, moduleInventory, swiftLibPath, outputDirectory, wrapper, errors);
}
WriteTypeDataBase (moduleDeclarations, outputDirectory);
}
void WriteTypeDataBase (List<ModuleDeclaration> moduleDeclarations, string outputDirectory)
{
string bindingsDir = Path.Combine (outputDirectory, "bindings");
Directory.CreateDirectory (bindingsDir);
foreach (ModuleDeclaration module in moduleDeclarations)
TypeMapper.TypeDatabase.Write (Path.Combine (bindingsDir, module.Name), module.Name);
}
void CompileModuleContents (ModuleDeclaration module, ModuleInventory moduleInventory, string swiftLibPath,
string outputDirectory, WrappingResult wrapper, ErrorHandling errors)
{
using (TempDirectoryFilenameProvider provider = new TempDirectoryFilenameProvider (null, true)) {
bool successfulOutput = false;
successfulOutput |= CompileProtocols (module.Protocols, provider, module, moduleInventory, swiftLibPath, outputDirectory, wrapper, errors);
successfulOutput |= CompileClasses (module.Classes, provider, module, moduleInventory, swiftLibPath, outputDirectory, wrapper, errors);
successfulOutput |= CompileStructs (module.Structs, provider, module, moduleInventory, swiftLibPath, outputDirectory, wrapper, errors);
successfulOutput |= CompileEnums (module.Enums, provider, module, moduleInventory, swiftLibPath, outputDirectory, wrapper, errors);
successfulOutput |= CompileExtensions (module.Extensions, provider, module, moduleInventory, swiftLibPath, outputDirectory, wrapper, errors);
successfulOutput |= CompileTopLevelEntities (provider, module, moduleInventory, swiftLibPath, outputDirectory, wrapper, errors);
if (!successfulOutput)
throw ErrorHelper.CreateError (ReflectorError.kCantHappenBase + 16, "binding-tools-for-swift could not generate any output. Check the logs and consider using '--verbose' for more information.");
}
}
bool CompileTopLevelEntities (TempDirectoryFilenameProvider provider,
ModuleDeclaration module, ModuleInventory moduleInventory, string swiftLibPath,
string outputDirectory, WrappingResult wrapper, ErrorHandling errors)
{
if (Verbose)
Console.Write ("Compiling top-level entities: ");
var use = new CSUsingPackages ("System", "System.Runtime.InteropServices");
var picl = new CSClass (CSVisibility.Internal, PIClassName (module.Name + "." + CompilerNames.GlobalFunctionClassName));
var usedPinvokes = new List<string> ();
var cl = CompileTLFuncs (module.TopLevelFunctions, module, moduleInventory,
swiftLibPath, outputDirectory, wrapper, errors, use, null, picl, usedPinvokes);
cl = CompileTLProps (module.TopLevelProperties, module, moduleInventory,
swiftLibPath, outputDirectory, wrapper, errors, use, cl, picl, usedPinvokes);
if (cl != null) {
string nameSpace = TypeMapper.MapModuleToNamespace (module.Name);
var nm = new CSNamespace (nameSpace);
var csfile = new CSFile (use, new CSNamespace [] { nm });
nm.Block.Add (cl);
nm.Block.Add (picl);
string csOutputFileName = string.Format ("{1}{0}.cs", nameSpace, cl.Name.Name);
string csOutputPath = Path.Combine (outputDirectory, csOutputFileName);
CodeWriter.WriteToFile (csOutputPath, csfile);
if (Verbose)
Console.WriteLine ("Success");
} else {
if (Verbose)
Console.WriteLine ("No top-level entities");
return false;
}
return true;
}
CSClass CompileTLProps (IEnumerable<PropertyDeclaration> props,
ModuleDeclaration module, ModuleInventory moduleInventory, string swiftLibPath,
string outputDirectory, WrappingResult wrapper, ErrorHandling errors,
CSUsingPackages use, CSClass cl, CSClass picl, List<string> usedPinvokes)
{
var properties = new List<CSProperty> ();
if (Verbose)
Console.WriteLine (props.Select (pd => pd.ToFullyQualifiedName ()).InterleaveCommas ());
foreach (PropertyDeclaration prop in props) {
if (prop.IsDeprecated || prop.IsUnavailable)
continue;
try {
cl = cl ?? new CSClass (CSVisibility.Public, CompilerNames.GlobalFunctionClassName);
// Calculated properties have a matching __method
string backingMethodName = ("__" + prop.Name);
CSMethod backingMethod = cl.Methods.FirstOrDefault (x => x.Name.Name == backingMethodName);
if (backingMethod == null)
CompileTLProp (prop, module.SwiftCompilerVersion, moduleInventory, use, wrapper, swiftLibPath, properties, cl, picl, usedPinvokes);
else
CompileTLCalculatedProp (prop, backingMethod, backingMethodName, cl);
} catch (Exception e) {
errors.Add (e);
}
}
if (properties.Count > 0) {
cl.Properties.AddRange (properties);
}
return cl;
}
void CompileTLCalculatedProp (PropertyDeclaration prop, CSMethod backingMethod, string methodName, CSClass cl)
{
var getter = prop.GetGetter ();
if (getter.IsPublicOrOpen) {
var setter = prop.GetSetter ();
bool hasSetter = setter != null && setter.IsPublicOrOpen;
string propName = TypeMapper.SanitizeIdentifier (prop.Name);
CSCodeBlock getBlock = CSCodeBlock.Create (CSReturn.ReturnLine (CSFunctionCall.Function (methodName)));
CSCodeBlock setBlock = null;
if (hasSetter)
setBlock = CSCodeBlock.Create (CSFunctionCall.FunctionLine (methodName, (CSIdentifier)"value"));
CSProperty property = new CSProperty (backingMethod.Type, CSMethodKind.Static, (CSIdentifier)prop.Name, CSVisibility.Public, getBlock, CSVisibility.Public, setBlock);
cl.Properties.Add (property);
}
}
void CompileTLProp (PropertyDeclaration prop, Version swiftLangVersion, ModuleInventory moduleInventory,
CSUsingPackages use, WrappingResult wrapper, string swiftLibPath,
List<CSProperty> properties, CSClass cl, CSClass picl, List<string> usedPinvokes)
{
var getter = prop.GetGetter ();
var setter = prop.GetSetter ();
var propType = MethodWrapping.GetPropertyType (prop, moduleInventory);
TLFunction getterWrapper = null;
TLFunction setterWrapper = null;
FunctionDeclaration setterWrapperFunc = null;
CSMethod piGetter = null;
CSMethod piSetter = null;
string piGetterName = null;
string piSetterName = null;
string piGetterRef = null;
string piSetterRef = null;
string syntheticClassName = prop.Module.Name + "." + CompilerNames.GlobalFunctionClassName;
string getWrapperName = MethodWrapping.WrapperName (prop.Module.Name, prop.Name, PropertyType.Getter, false, prop.IsExtension, prop.IsStatic);
getterWrapper = FindTLPropWrapper (prop, getWrapperName, wrapper);
var getterWrapperFunc = FindEquivalentFunctionDeclarationForWrapperFunction (getterWrapper, TypeMapper, wrapper);
piGetterName = PIMethodName ((string)null, getterWrapper.Name, PropertyType.Getter);
piGetterName = Uniqueify (piGetterName, usedPinvokes);
usedPinvokes.Add (piGetterName);
piGetterRef = PIClassName (syntheticClassName) + "." + piGetterName;
piGetter = TLFCompiler.CompileMethod (getterWrapperFunc, use, PInvokeName (wrapper.ModuleLibPath, swiftLibPath),
getterWrapper.MangledName, piGetterName, true, true, false);
picl.Methods.Add (piGetter);
if (!prop.IsLet && (prop.Storage != StorageKind.Computed ||
(prop.Storage == StorageKind.Computed && setter != null))) {
string setWrapperName = MethodWrapping.WrapperName (prop.Module.Name, prop.Name, PropertyType.Setter, false, prop.IsExtension, prop.IsStatic);
setterWrapper = FindTLPropWrapper (prop, setWrapperName, wrapper);
setterWrapperFunc = FindEquivalentFunctionDeclarationForWrapperFunction (setterWrapper, TypeMapper, wrapper);
piSetterName = PIMethodName ((string)null, setterWrapper.Name, PropertyType.Setter);
piSetterName = Uniqueify (piSetterName, usedPinvokes);
usedPinvokes.Add (piSetterName);
piSetterRef = PIClassName (syntheticClassName) + "." + piSetterName;
piSetter = TLFCompiler.CompileMethod (setterWrapperFunc, use, PInvokeName (wrapper.ModuleLibPath, swiftLibPath),
setterWrapper.MangledName, piSetterName, true, true, false);
picl.Methods.Add (piSetter);
}
var propName = prop.Name;
var isProtocolListType = TypeMapper.IsCompoundProtocolListType (prop.TypeSpec);
CSProperty wrapperProp = null;
CSMethod wrapperGetter = null, wrapperSetter = null;
if (isProtocolListType) {
// Yay! Grossness ahead.
// Swift allows properties to be protocol list types, which means that in C# we need a function that returns
// a generic type with constraints, but C# properties can't be generic with a constraint, so I have to make the
// properties appear as a pair of generic methods instead. In the case of top-level property, there may not be
// an accessor function associated with the property, so instead we need to fake the accessor functions and
// synthesize them if needed.
if (getter == null) {
getter = new FunctionDeclaration () {
Name = "Get" + propName,
Access = Accessibility.Public,
IsStatic = true,
Module = prop.Module,
OperatorType = OperatorType.None,
ReturnTypeName = propType.ToString ()
};
getter.ParameterLists.Add (new List<ParameterItem> ());
}
wrapperGetter = TLFCompiler.CompileMethod (getter, use, wrapper.ModuleLibPath, null, "Get" + propName, false, false, true);
if (piSetter != null) {
if (setter == null) {
setter = new FunctionDeclaration () {
Name = "Set" + propName,
Access = Accessibility.Public,
IsStatic = true,
Module = prop.Module,
OperatorType = OperatorType.None,
ReturnTypeName = "()"
};
var pi = new ParameterItem () {
IsInOut = false,
PrivateName = "value",
PublicName = "value",
TypeName = propType.ToString (),
IsVariadic = false
};
setter.ParameterLists.Add (new List<ParameterItem> ());
setter.ParameterLists [0].Add (pi);
}
wrapperSetter = TLFCompiler.CompileMethod (setter, use, wrapper.ModuleLibPath, null, "Set" + propName, false, false, true);
var oldParam = wrapperSetter.Parameters [0];
// Why you ask? Because I was too clever for the nonce.
// In CompileMethod, deep, deep inside, there's code to prevent accepting a parameter named after a C# keyword (possibly
// legal in swift), but that's not how properties work when we marshal it later, so we force it back to value because
// it's outside of a property context in this case. We can't fix it inside CompileMethod because there is no context
// to determine if it's a property context and refactoring to include the context is ornerous.
wrapperSetter.Parameters [0] = new CSParameter (oldParam.CSType, new CSIdentifier ("value"), oldParam.ParameterKind);
}
} else {
wrapperProp = TLFCompiler.CompileProperty (prop.Name, use,
propType, piGetter != null, piSetter != null,
prop.IsStatic ? CSMethodKind.Static : CSMethodKind.None);
if (TopLevelFunctionCompiler.TypeSpecCanThrow (getter.ReturnTypeSpec, false))
TopLevelFunctionCompiler.DecorateTypeWithThrows (wrapperProp.PropType, use);
}
if (piGetter != null) {
var useLocals = new List<string> {
wrapperGetter?.Name.Name ?? propName,
cl.Name.Name
};
var marshaler = new MarshalEngine (use, useLocals, TypeMapper, swiftLangVersion);
var codeBlock = wrapperProp != null ? wrapperProp.Getter : wrapperGetter.Body;
codeBlock.AddRange (marshaler.MarshalFunctionCall (getterWrapperFunc, false,
piGetterRef, new CSParameterList (), getterWrapperFunc, prop.TypeSpec,
wrapperProp?.PropType ?? wrapperGetter.Type, null, new CSSimpleType (cl.Name.Name), false, getter));
}
if (piSetter != null) {
var useLocals = new List<string> {
wrapperSetter?.Name.Name ?? propName,
cl.Name.Name,
"value"
};
var valParm = new CSParameter (wrapperProp?.PropType ?? wrapperGetter.Type, new CSIdentifier ("value"));
var marshaler = new MarshalEngine (use, useLocals, TypeMapper, swiftLangVersion);
var codeBlock = wrapperProp != null ? wrapperProp.Setter : wrapperSetter.Body;
codeBlock.AddRange (marshaler.MarshalFunctionCall (setterWrapperFunc, false,
piSetterRef, new CSParameterList (valParm), getterWrapperFunc, null, CSSimpleType.Void,
null, new CSSimpleType (cl.Name.Name), false, setter));
}
if (wrapperProp != null) {
wrapperProp = new CSProperty (wrapperProp.PropType, CSMethodKind.Static, wrapperProp.Name,
CSVisibility.Public, wrapperProp.Getter, CSVisibility.Public, wrapperProp.Setter);
cl.Properties.Add (wrapperProp);
} else {
cl.Methods.Add (wrapperGetter);
if (wrapperSetter != null)
cl.Methods.Add (wrapperSetter);
}
}
TLFunction FindTLPropWrapper (PropertyDeclaration prop, string wrapperName, WrappingResult wrapper)
{
OverloadInventory overload = null;
if (!wrapper.Contents.Functions.TryGetValue (new SwiftName (wrapperName, false), out overload)) {
throw ErrorHelper.CreateError (ReflectorError.kCompilerReferenceBase + 9, $"Unable to find wrapping function {wrapperName} for {prop.ToFullyQualifiedName ()}.");
}
if (overload.Functions.Count > 1) {
throw ErrorHelper.CreateError (ReflectorError.kCompilerReferenceBase + 10, $"Expected exactly one overload for wrapping function {wrapperName} for {prop.ToFullyQualifiedName ()}, but got {overload.Functions.Count}.");
}
var wrapperTlf = overload.Functions [0];
return wrapperTlf;
}
CSClass CompileTLFuncs (IEnumerable<FunctionDeclaration> funcs,
ModuleDeclaration module, ModuleInventory moduleInventory, string swiftLibPath,
string outputDirectory, WrappingResult wrapper, ErrorHandling errors,
CSUsingPackages use, CSClass cl, CSClass picl, List<string> usedPinvokeNames)
{
if (Verbose)
Console.WriteLine (funcs.Select (pd => pd.ToFullyQualifiedName ()).InterleaveCommas ());
var methods = new List<CSMethod> ();
foreach (FunctionDeclaration func in funcs) {
try {
if (func.IsProperty)
continue;
// error already generated
if (func.IsDeprecated || func.IsUnavailable)
continue;
if (errors.SkippedFunctions.Contains (func.ToFullyQualifiedName (true))) {
var ex = ErrorHelper.CreateWarning (ReflectorError.kCompilerBase + 13, $"Skipping C# wrapping top-level function {func.ToFullyQualifiedName (true)}, due to a previous error.");
errors.Add (ex);
continue;
}
CompileTopLevelFunction (func, funcs, moduleInventory, use, wrapper, swiftLibPath, methods, picl, usedPinvokeNames);
} catch (Exception e) {
errors.Add (e);
}
}
if (methods.Count > 0) {
cl = cl ?? new CSClass (CSVisibility.Public, CompilerNames.GlobalFunctionClassName);
cl.Methods.AddRange (methods);
}
return cl;
}
void CompileTopLevelFunction (FunctionDeclaration func, IEnumerable<FunctionDeclaration> peerFunctions, ModuleInventory moduleInventory, CSUsingPackages use,
WrappingResult wrapper, string swiftLibPath, List<CSMethod> methods, CSClass picl, List<string> usedPinvokeNames)
{
if (MethodWrapping.FuncNeedsWrapping (func, TypeMapper)) {
CompileToWrapperFunction (func, peerFunctions, moduleInventory, use, wrapper, swiftLibPath, methods, picl, usedPinvokeNames);
} else {
CompileToDirectFunction (func, peerFunctions, func.Parent, moduleInventory, use, wrapper, swiftLibPath, methods, picl, usedPinvokeNames);
}
}
void CompileToWrapperFunction (FunctionDeclaration func, IEnumerable<FunctionDeclaration> peerFunctions,
ModuleInventory moduleInventory, CSUsingPackages use,
WrappingResult wrapper, string swiftLibPath, List<CSMethod> methods, CSClass picl,
List<string> usedPinvokeNames)
{
var finder = new FunctionDeclarationWrapperFinder (TypeMapper, wrapper);
var wrapperFunc = finder.FindWrapperForTopLevelFunction (func);
if (wrapperFunc == null)
throw ErrorHelper.CreateError (ReflectorError.kCompilerReferenceBase + 12, $"Unable to find wrapper function for {func.ToFullyQualifiedName ()}.");
var wrapperFunction = FindEquivalentTLFunctionForWrapperFunction (wrapperFunc, TypeMapper, wrapper);
var functionPIBaseName = new SwiftName (TypeMapper.SanitizeIdentifier (wrapperFunc.Name), false);
string operatorFunctionName = func.IsOperator ? ToOperatorName (func) : null;
var homonymSuffix = Homonyms.HomonymSuffix (func, peerFunctions, TypeMapper);
var pinvokeMethodName = PIFuncName (functionPIBaseName) + homonymSuffix;
pinvokeMethodName = MarshalEngine.Uniqueify (pinvokeMethodName, usedPinvokeNames);
usedPinvokeNames.Add (pinvokeMethodName);
string pinvokeMethodRef = PIClassName (func.Module.Name + "." + CompilerNames.GlobalFunctionClassName) + "." + pinvokeMethodName + homonymSuffix;
var piMethod = TLFCompiler.CompileMethod (wrapperFunc, use, PInvokeName (wrapper.ModuleLibPath, swiftLibPath),
wrapperFunction.MangledName, pinvokeMethodName, true, true, false);
picl.Methods.Add (piMethod);
var publicMethodOrig = TLFCompiler.CompileMethod (func, use, PInvokeName (swiftLibPath),
mangledName: "", operatorFunctionName,
false, false, false);
CSIdentifier wrapperName = GetMethodWrapperName (func, publicMethodOrig, homonymSuffix);
CSVisibility visibility = GetMethodWrapperVisibility (func, publicMethodOrig);
// rebuild the method as static
var publicMethod = new CSMethod (visibility, CSMethodKind.Static, publicMethodOrig.Type,
wrapperName, publicMethodOrig.Parameters, publicMethodOrig.Body);
publicMethod.GenericParameters.AddRange (publicMethodOrig.GenericParameters);
publicMethod.GenericConstraints.AddRange (publicMethodOrig.GenericConstraints);
var localIdents = new List<string> {
publicMethod.Name.Name, pinvokeMethodName
};
localIdents.AddRange (publicMethod.Parameters.Select (p => p.Name.Name));
var marshaler = new MarshalEngine (use, localIdents, TypeMapper, wrapper.Module.SwiftCompilerVersion);
var lines = marshaler.MarshalFunctionCall (wrapperFunc, false, pinvokeMethodRef,
publicMethod.Parameters, func, func.ReturnTypeSpec, publicMethod.Type,
null, null, false, func, false, -1, func.HasThrows);
publicMethod.Body.AddRange (lines);
methods.Add (publicMethod);
}
void CompileToDirectFunction (FunctionDeclaration func, IEnumerable<FunctionDeclaration> peerFunctions, BaseDeclaration context,
ModuleInventory moduleInventory, CSUsingPackages use,
WrappingResult wrapper, string swiftLibPath, List<CSMethod> methods, CSClass picl,
List<string> usedPinvokeNames)
{
var tlf = XmlToTLFunctionMapper.ToTLFunction (func, moduleInventory, TypeMapper);
if (tlf == null)
throw ErrorHelper.CreateError (ReflectorError.kCompilerReferenceBase + 15, $"Unable to find function for declaration {func.ToFullyQualifiedName (true)}.");
var homonymSuffix = Homonyms.HomonymSuffix (func, peerFunctions, TypeMapper);
CompileToDirectFunction (func, tlf, homonymSuffix, context, use, wrapper, swiftLibPath, methods, picl, usedPinvokeNames);
}
void CompileToDirectFunction (FunctionDeclaration func, TLFunction tlf, string homonymSuffix, BaseDeclaration context,
CSUsingPackages use, WrappingResult wrapper, string swiftLibPath, List<CSMethod> methods, CSClass picl,
List<string> usedPinvokeNames)
{
// FIXME - need to do operators
if (tlf.Operator != OperatorType.None)
return;
var baseName = TypeMapper.SanitizeIdentifier (tlf.Name.Name);
var pinvokeMethodName = PIFuncName (baseName + homonymSuffix);
pinvokeMethodName = MarshalEngine.Uniqueify (pinvokeMethodName, usedPinvokeNames);
usedPinvokeNames.Add (pinvokeMethodName);
var pinvokeMethodRef = PIClassName ($"{func.Module.Name}.{CompilerNames.GlobalFunctionClassName}") + "." + pinvokeMethodName;
var piMethod = TLFCompiler.CompileMethod (func, use, PInvokeName (swiftLibPath),
tlf.MangledName, pinvokeMethodName, true, true, false);
picl.Methods.Add (piMethod);
var publicMethodOrig = TLFCompiler.CompileMethod (func, use, PInvokeName (swiftLibPath),
tlf.MangledName, null, false, false, false);
CSIdentifier wrapperName = GetMethodWrapperName (func, publicMethodOrig, homonymSuffix);
CSVisibility visibility = GetMethodWrapperVisibility (func, publicMethodOrig);
// rebuild the method as static
var publicMethod = new CSMethod (visibility, CSMethodKind.Static, publicMethodOrig.Type,
wrapperName, publicMethodOrig.Parameters, publicMethodOrig.Body);
publicMethod.GenericParameters.AddRange (publicMethodOrig.GenericParameters);
publicMethod.GenericConstraints.AddRange (publicMethodOrig.GenericConstraints);
var localIdents = new List<string> {
publicMethod.Name.Name, pinvokeMethodName
};
localIdents.AddRange (publicMethod.Parameters.Select (p => p.Name.Name));
var marshaler = new MarshalEngine (use, localIdents, TypeMapper, wrapper.Module.SwiftCompilerVersion);
var lines = marshaler.MarshalFunctionCall (func, false, pinvokeMethodRef, publicMethod.Parameters,
func, func.ReturnTypeSpec, publicMethod.Type, null, null, false, func,
false, -1, func.HasThrows);
publicMethod.Body.AddRange (lines);
methods.Add (publicMethod);
}
CSIdentifier GetMethodWrapperName (FunctionDeclaration func, CSMethod method, string homonymSuffix)
{
string prefix = func.IsProperty ? "__" : "";
return new CSIdentifier (prefix + method.Name.Name + homonymSuffix);
}
CSVisibility GetMethodWrapperVisibility (FunctionDeclaration func, CSMethod method)
{
return func.IsProperty ? CSVisibility.Private: method.Visibility;
}
public static void ReportCompileStatus (IEnumerable<TypeDeclaration> items, string type)
{
ReportCompileStatus (items.Select (pd => pd.ToFullyQualifiedName ()), type);
}
public static void ReportCompileStatus (IEnumerable<string> items, string type)
{
Console.Write ($"Compiling {type}: ");
if (items.Any ())
Console.WriteLine (items.InterleaveCommas ());
else
Console.WriteLine ($"No {type} detected");
}
bool CompileEnums (IEnumerable<EnumDeclaration> enums, TempDirectoryFilenameProvider provider,
ModuleDeclaration module, ModuleInventory moduleInventory, string swiftLibPath,
string outputDirectory, WrappingResult wrapper, ErrorHandling errors)
{
if (Verbose)
ReportCompileStatus (enums, "enums");
if (!enums.Any ())
return false;
var trivialEnums = enums.Where (e => (e.Access == Accessibility.Public || e.Access == Accessibility.Open) &&
!(e.IsDeprecated || e.IsUnavailable) &&
(e.IsTrivial || (e.IsIntegral && e.IsHomogenous && e.Inheritance.Count == 0))).ToList ();
var nontrivialEnums = enums.Where (e => (e.Access == Accessibility.Public || e.Access == Accessibility.Open) &&
!(e.IsDeprecated || e.IsUnavailable) &&
!(e.IsTrivial || (e.IsTrivial || (e.IsIntegral && e.IsHomogenous && e.Inheritance.Count == 0)))).ToList ();
CompileTrivialEnums (trivialEnums, provider, module, moduleInventory, swiftLibPath,
outputDirectory, wrapper, errors);
CompileNontrivialEnums (nontrivialEnums, provider, module, moduleInventory, swiftLibPath,
outputDirectory, wrapper, errors);
return true;
}
void CompileInnerEnumInto (EnumDeclaration enumDecl, CSClass target, ModuleInventory modInventory, CSUsingPackages use,
WrappingResult wrapper, string swiftLibraryPath, List<CSClass> pinvokes, ErrorHandling errors)
{
// trivial
if (enumDecl.IsTrivial || (enumDecl.IsIntegral && enumDecl.IsHomogenous && enumDecl.Inheritance.Count == 0)) {
var csEnum = CompileTrivialEnum (enumDecl, modInventory, use, wrapper, swiftLibraryPath);
CSClass picl = null;
var csExt = CompileTrivialEnumExtensions (enumDecl, modInventory, use, wrapper, swiftLibraryPath, out picl, errors);
target.InnerEnums.Add (csEnum);
if (csExt != null) {
target.InnerClasses.Add (csExt);
target.InnerClasses.Add (picl);
}
} else { // non-trivial
var swiftEnumName = XmlToTLFunctionMapper.ToSwiftClassName (enumDecl);
string enumName = StubbedClassName (swiftEnumName);
string enumCaseName = enumName + "Cases";
var enumCase = CompileEnumCases (enumDecl, enumCaseName);
target.InnerEnums.Add (enumCase);
var enumClass = CompileEnumClass (enumDecl, enumCaseName, enumCase, use, modInventory, swiftLibraryPath, wrapper, errors, pinvokes);
target.InnerClasses.Add (enumClass);
}
}
void CompileNontrivialEnums (IEnumerable<EnumDeclaration> enums, TempDirectoryFilenameProvider provider,
ModuleDeclaration module, ModuleInventory moduleInventory, string swiftLibPath,
string outputDirectory, WrappingResult wrapper, ErrorHandling errors)
{
foreach (EnumDeclaration enumDecl in enums) {
if (enumDecl.Access.IsPrivateOrInternal ())
continue;
try {
if (errors.SkippedTypes.Contains (enumDecl.ToFullyQualifiedName (true))) {
var ex = ErrorHelper.CreateWarning (ReflectorError.kTypeMapBase + 19, $"Skipping C# wrapping enumeration {enumDecl.ToFullyQualifiedName (true)}, due to a previous error.");
continue;
}
var useEnums = new CSUsingPackages ("System", "System.Runtime.InteropServices");
string nameSpace = TypeMapper.MapModuleToNamespace (module.Name);
var nmEnums = new CSNamespace (nameSpace);
var enumFile = new CSFile (useEnums, new CSNamespace [] { nmEnums });
var swiftEnumName = XmlToTLFunctionMapper.ToSwiftClassName (enumDecl);
string enumName = StubbedClassName (swiftEnumName);
string enumCaseName = enumName + "Cases";
var enumCase = CompileEnumCases (enumDecl, enumCaseName);
nmEnums.Block.Add (enumCase);
var pinvokes = new List<CSClass> ();
var enumClass = CompileEnumClass (enumDecl, enumCaseName, enumCase, useEnums, moduleInventory, swiftLibPath, wrapper, errors, pinvokes);
nmEnums.Block.Add (enumClass);
nmEnums.Block.AddRange (pinvokes);
// FIXME - need to use the name of the CSClass for the enum
string enumOutFileName = String.Format ("{0}{1}.cs", enumClass.Name.Name, enumDecl.Module.Name);
WriteCSFile (enumOutFileName, outputDirectory, enumFile);
} catch (Exception e) {
errors.Add (e);
}
}
}
CSClass CompileEnumClass (EnumDeclaration enumDecl, string enumCaseName, CSEnum enumCase, CSUsingPackages use,
ModuleInventory moduleInventory, string swiftLibPath, WrappingResult wrapper,
ErrorHandling errors, List<CSClass> pinvokes)
{
var swiftEnumName = XmlToTLFunctionMapper.ToSwiftClassName (enumDecl);
var classContents = XmlToTLFunctionMapper.LocateClassContents (moduleInventory, swiftEnumName);
if (classContents == null)
throw ErrorHelper.CreateError (ReflectorError.kCompilerReferenceBase + 17, $"Unable to find struct contents for {enumDecl.ToFullyQualifiedName ()}.");
string enumName = StubbedClassName (swiftEnumName);
var enumClass = new CSClass (CSVisibility.Public, new CSIdentifier (enumName));
var enumPI = new CSClass (CSVisibility.Internal, PIClassName (swiftEnumName));
pinvokes.Add (enumPI);
var usedPinvokeNames = new List<string> ();
use.AddIfNotPresent (typeof (SwiftNativeValueType));
enumClass.Inheritance.Add (typeof (SwiftNativeValueType));
use.AddIfNotPresent (typeof (ISwiftEnum));
enumClass.Inheritance.Add (typeof (ISwiftEnum));
var enumContents = moduleInventory.FindClass (enumDecl.ToFullyQualifiedName (true));
if (enumContents == null) {
throw ErrorHelper.CreateError (ReflectorError.kCompilerReferenceBase + 18, $"Unable to location class contents for enum {enumDecl.ToFullyQualifiedName (true)}.");
}
AddGenerics (enumClass, enumDecl, enumContents, use);
string witName = enumContents.WitnessTable.ValueWitnessTable != null ? enumContents.WitnessTable.ValueWitnessTable.MangledName.Substring (1) : "";
string nomSym = enumContents.TypeDescriptor.MangledName.Substring (1);
string metaDataSym = enumContents.DirectMetadata != null ? enumContents.DirectMetadata.MangledName.Substring (1) : "";
use.AddIfNotPresent (typeof (SwiftEnumTypeAttribute));
MakeSwiftEnumTypeAttribute (PInvokeName (swiftLibPath), nomSym, metaDataSym, witName).AttachBefore (enumClass);
string libPath = PInvokeName (wrapper.ModuleLibPath, swiftLibPath);
ImplementValueTypeIDisposable (enumClass, use);
AddInheritedProtocols (enumDecl, enumClass, enumContents, PInvokeName (swiftLibPath), use, errors);
ImplementMethods (enumClass, enumPI, usedPinvokeNames, swiftEnumName, classContents, enumDecl, use, wrapper, tlf => true, swiftLibPath, errors);
ImplementProperties (enumClass, enumPI, usedPinvokeNames, enumDecl, classContents, null, use, wrapper, true, false, tlf => true, swiftLibPath, errors);
ImplementSubscripts (enumClass, enumPI, usedPinvokeNames, enumDecl, enumDecl.AllSubscripts (), classContents, null, use, wrapper, true, tlf => true, swiftLibPath, errors);
var usedNames = new List<string> {
enumCaseName,
enumName
};
for (int i = 0; i < enumDecl.Elements.Count; i++) {
var elem = enumDecl.Elements [i];
var factoryFunc = FindEnumFactoryWrapper (enumDecl, elem, wrapper);
if (factoryFunc == null) {
ErrorHelper.CreateError (ReflectorError.kCompilerReferenceBase + 19, $"Unable to find a wrapper function for a factory for {enumDecl.ToFullyQualifiedName (true)}.{elem.Name}.");
}
var factoryFuncDecl = FindEquivalentFunctionDeclarationForWrapperFunction (factoryFunc, TypeMapper, wrapper);
var factoryName = PIMethodName (swiftEnumName, factoryFunc.Name);
factoryName = MarshalEngine.Uniqueify (factoryName, usedPinvokeNames);
usedPinvokeNames.Add (factoryName);
var factoryRef = PIClassName (swiftEnumName) + "." + factoryName;
var factoryPI = TLFCompiler.CompileMethod (factoryFuncDecl, use, libPath, factoryFunc.MangledName, factoryName,
true, false, false);
enumPI.Methods.Add (factoryPI);
var factoryMethod = CompileEnumFactory (enumDecl, elem, enumCase.Values [i].Name.Name, factoryFuncDecl,
factoryRef, use, wrapper);
enumClass.Methods.Add (factoryMethod);
}
for (int i = 0; i < enumDecl.Elements.Count; i++) {
var elem = enumDecl.Elements [i];
if (!elem.HasType)
continue;
var payloadFunc = FindEnumPayloadWrapper (enumDecl, elem, wrapper);
if (payloadFunc == null) {
throw ErrorHelper.CreateError (ReflectorError.kCompilerReferenceBase + 20, $"Unable to find a wrapper function for a payload for {enumDecl.ToFullyQualifiedName (true)}.{ elem.Name}.");
}
var payloadFuncDecl = FindEquivalentFunctionDeclarationForWrapperFunction (payloadFunc, TypeMapper, wrapper);
string payloadName = PIMethodName (swiftEnumName, payloadFunc.Name);
payloadName = MarshalEngine.Uniqueify (payloadName, usedPinvokeNames);
usedPinvokeNames.Add (payloadName);
string payloadRef = PIClassName (swiftEnumName) + "." + payloadName;
var payloadPI = TLFCompiler.CompileMethod (payloadFuncDecl, use, libPath, payloadFunc.MangledName, payloadName,
true, false, false);
enumPI.Methods.Add (payloadPI);
CompileEnumPayload (enumClass, enumDecl, elem, enumClass.ToCSType(),
new CSSimpleType(enumCase.Name.Name),
enumCase.Values [i].Name.Name, payloadFuncDecl,
payloadRef, use, wrapper);
}
var caseFinderFunc = FindEnumCaseFinderWrapper (enumDecl, wrapper);
if (caseFinderFunc == null) {
throw ErrorHelper.CreateError (ReflectorError.kCompilerReferenceBase + 21, $"Unable to find a wrapper function for a case finder for {enumDecl.ToFullyQualifiedName (true)}.");
}
var caseFinderWrapperFunc = FindEquivalentFunctionDeclarationForWrapperFunction (caseFinderFunc, TypeMapper, wrapper);
var caseFinderName = PIMethodName (swiftEnumName, caseFinderFunc.Name);
caseFinderName = MarshalEngine.Uniqueify (caseFinderName, usedPinvokeNames);
usedPinvokeNames.Add (caseFinderName);
string caseFinderRef = PIClassName (swiftEnumName) + "." + caseFinderName;
CSMethod caseFinderPI = TLFCompiler.CompileMethod (caseFinderWrapperFunc, use, libPath, caseFinderFunc.MangledName, caseFinderName,
true, false, false);
enumPI.Methods.Add (caseFinderPI);
string finderMethodName = "Case";
var localUsedNames1 = new List<string> (usedNames);
MarshalEngine marshal1 = new MarshalEngine (use, localUsedNames1, TypeMapper, wrapper.Module.SwiftCompilerVersion);
var callingCode1 = marshal1.MarshalFunctionCall (caseFinderWrapperFunc, false, caseFinderRef,
new CSParameterList (), enumDecl, caseFinderWrapperFunc.ReturnTypeSpec, new CSSimpleType (enumCaseName),
caseFinderWrapperFunc.ParameterLists.Last () [0].TypeSpec, enumClass.ToCSType (), true, caseFinderWrapperFunc, true).ToList ();
var caseProp = new CSProperty (new CSSimpleType (enumCaseName), CSMethodKind.None, new CSIdentifier (finderMethodName),
CSVisibility.Public, callingCode1, CSVisibility.Public, null);
enumClass.Properties.Add (caseProp);
if (enumDecl.ContainsGenericParameters) {
enumClass.Methods.AddRange (MakeClassConstructor (enumClass, enumPI, usedPinvokeNames, enumDecl, enumContents, use, libPath, false));
}
CompileInnerNominalsInto (enumDecl, enumClass, moduleInventory, use, wrapper, swiftLibPath, pinvokes, errors);
TypeNameAttribute (enumDecl, use).AttachBefore (enumClass);
return enumClass;
}
CSMethod CompileEnumFactory (EnumDeclaration enumDecl, EnumElement element, string csCaseName, FunctionDeclaration wrappingFunc,
string pinvokeRef, CSUsingPackages use, WrappingResult wrapper)
{
// format should be:
// public static EnumType NewCaseName ()
// {
// EnumType retval = new Parameter();
// unsafe {
// fixed (byte *retvalSwiftDataPtr = StructMarshal.Marshaler.PrepareValueType(this)) {
// Pinvoke.ToSwift(new IntPtr(retvalSwiftDataPtr));
// }
// }
// return retval;
// }
// or
// public static EnumType NewCaseName(CSType value)
// {
// EnumType retval = new Parameter()
// unsafe {
// fixed (byte *retvalSwiftDataPtr = StructMarshal.Marshaler.PrepareValueType(this)) {
// // marshal code for value
// Pinvoke.ToSwift(new IntPtr(retvalSwiftDataPtr), whateverMarshaledValueIs);
// }
// }
// return retval;
// }
//
// How do we do this?
// The problem is that there is no original function to do this since the underlying code just wrote the
// wrapper directly.
// What we're going to do is write a facsimile of what the original function declaration would have been:
// public static func NewCaseName(val: IfAny) -> SwiftEnumType
// and then we'll use MarshalFunctionCall to do that work for us.
var returnTypeSpec = enumDecl.ToTypeSpec ();
var factoryDecl = new FunctionDeclaration {
Module = enumDecl.Module,
Parent = enumDecl,
Name = $"New{csCaseName}",
Access = Accessibility.Public,