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 pathSwiftInterfaceReflector.cs
2302 lines (2044 loc) · 81.5 KB
/
SwiftInterfaceReflector.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.IO;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Antlr4.Runtime;
using Antlr4.Runtime.Misc;
using Antlr4.Runtime.Tree;
using static SwiftInterfaceParser;
using System.Text;
using Dynamo;
using SwiftReflector.TypeMapping;
using SwiftReflector.SwiftXmlReflection;
namespace SwiftReflector.SwiftInterfaceReflector {
public class SwiftInterfaceReflector : SwiftInterfaceBaseListener {
// swift-interface-format-version: 1.0
const string kSwiftInterfaceFormatVersion = "// swift-interface-format-version:";
// swift-compiler-version: Apple Swift version 5.3 (swiftlang-1200.0.29.2 clang-1200.0.30.1)
const string kSwiftCompilerVersion = "// swift-compiler-version: ";
// swift-module-flags: -target x86_64-apple-macosx10.9 -enable-objc-interop -ena
const string kSwiftModuleFlags = "// swift-module-flags:";
internal const string kModuleName = "module-name";
internal const string kTarget = "target";
internal const string kIgnore = "IGNORE";
internal const string kInheritanceKind = "inheritanceKind";
internal const string kModule = "module";
internal const string kFunc = "func";
internal const string kType = "type";
internal const string kName = "name";
internal const string kFinal = "final";
internal const string kPublic = "public";
internal const string kPrivate = "private";
internal const string kInternal = "internal";
internal const string kOpen = "open";
internal const string kPublicCap = "Public";
internal const string kPrivateCap = "Private";
internal const string kInternalCap = "Internal";
internal const string kOpenCap = "Open";
internal const string kFilePrivate = "fileprivate";
internal const string kStatic = "static";
internal const string kIsStatic = "isStatic";
internal const string kOptional = "optional";
internal const string kObjC = "objc";
internal const string kExtension = "extension";
internal const string kProtocol = "protocol";
internal const string kClass = "class";
internal const string kInnerClasses = "innerclasses";
internal const string kStruct = "struct";
internal const string kInnerStructs = "innerstructs";
internal const string kEnum = "enum";
internal const string kInnerEnums = "innerenums";
internal const string kMutating = "mutating";
internal const string kRequired = "required";
internal const string kAssociatedTypes = "associatedtypes";
internal const string kAssociatedType = "associatedtype";
internal const string kDefaultType = "defaulttype";
internal const string kConformingProtocols = "conformingprotocols";
internal const string kConformingProtocol = "conformingprotocol";
internal const string kMembers = "members";
internal const string kConvenience = "convenience";
internal const string kParameterLists = "parameterlists";
internal const string kParameterList = "parameterlist";
internal const string kParameter = "parameter";
internal const string kParam = "param";
internal const string kGenericParameters = "genericparameters";
internal const string kWhere = "where";
internal const string kRelationship = "relationship";
internal const string kEquals = "equals";
internal const string kInherits = "inherits";
internal const string kInherit = "inherit";
internal const string kIndex = "index";
internal const string kGetSubscript = "get_subscript";
internal const string kSetSubscript = "set_subscript";
internal const string kOperator = "operator";
internal const string kLittlePrefix = "prefix";
internal const string kLittlePostfix = "postfix";
internal const string kPrefix = "Prefix";
internal const string kPostfix = "Postfix";
internal const string kInfix = "Infix";
internal const string kDotCtor = ".ctor";
internal const string kDotDtor = ".dtor";
internal const string kNewValue = "newValue";
internal const string kOperatorKind = "operatorKind";
internal const string kPublicName = "publicName";
internal const string kPrivateName = "privateName";
internal const string kKind = "kind";
internal const string kNone = "None";
internal const string kLittleUnknown = "unknown";
internal const string kUnknown = "Unknown";
internal const string kOnType = "onType";
internal const string kAccessibility = "accessibility";
internal const string kIsVariadic = "isVariadic";
internal const string kTypeDeclaration = "typedeclaration";
internal const string kIsAsync = "isAsync";
internal const string kProperty = "property";
internal const string kIsProperty = "isProperty";
internal const string kStorage = "storage";
internal const string kComputed = "Computed";
internal const string kEscaping = "escaping";
internal const string kAutoClosure = "autoclosure";
internal const string kAttributes = "attributes";
internal const string kAttribute = "attribute";
internal const string kAttributeParameterList = "attributeparameterlist";
internal const string kAttributeParameter = "attributeparameter";
internal const string kLabel = "Label";
internal const string kLiteral = "Literal";
internal const string kSeparator = "Separator";
internal const string kSublist = "Sublist";
internal const string kValue = "Value";
internal const string kObjCSelector = "objcSelector";
internal const string kDeprecated = "deprecated";
internal const string kUnavailable = "unavailable";
internal const string kAvailable = "available";
internal const string kIntroduced = "introduced";
internal const string kObsoleted = "obsoleted";
internal const string kElements = "elements";
internal const string kElement = "element";
internal const string kIntValue = "intValue";
internal const string kRawType = "rawType";
internal const string kRawValue = "RawValue";
internal const string kTypeAliases = "typealiases";
internal const string kTypeAlias = "typealias";
internal const string kSuperclass = "superclass";
Stack<XElement> currentElement = new Stack<XElement> ();
Version interfaceVersion;
Version compilerVersion;
List<string> importModules = new List<string> ();
List<XElement> operators = new List<XElement> ();
List<Tuple<Function_declarationContext, XElement>> functions = new List<Tuple<Function_declarationContext, XElement>> ();
List<XElement> extensions = new List<XElement> ();
Dictionary<string, string> moduleFlags = new Dictionary<string, string> ();
List<string> nominalTypes = new List<string> ();
List<string> classes = new List<string> ();
List<XElement> associatedTypesWithConformance = new List<XElement> ();
List<XElement> unknownInheritance = new List<XElement> ();
List<XElement> typeAliasMap = new List<XElement> ();
string moduleName;
TypeDatabase typeDatabase;
IModuleLoader moduleLoader;
public SwiftInterfaceReflector (TypeDatabase typeDatabase, IModuleLoader moduleLoader)
{
this.typeDatabase = Exceptions.ThrowOnNull (typeDatabase, nameof (typeDatabase));
this.moduleLoader = Exceptions.ThrowOnNull (moduleLoader, nameof (moduleLoader));
}
public void Reflect (string inFile, Stream outStm)
{
Exceptions.ThrowOnNull (inFile, nameof (inFile));
Exceptions.ThrowOnNull (outStm, nameof (outStm));
var xDocument = Reflect (inFile);
xDocument.Save (outStm);
currentElement.Clear ();
}
public XDocument Reflect (string inFile)
{
try {
Exceptions.ThrowOnNull (inFile, nameof (inFile));
if (!File.Exists (inFile))
throw new ParseException ($"Input file {inFile} not found");
var fileName = Path.GetFileName (inFile);
moduleName = fileName.Split ('.') [0];
var module = new XElement (kModule);
currentElement.Push (module);
var desugarer = new SyntaxDesugaringParser (inFile);
var desugaredResult = desugarer.Desugar ();
var charStream = CharStreams.fromString (desugaredResult);
var lexer = new SwiftInterfaceLexer (charStream);
var tokenStream = new CommonTokenStream (lexer);
var parser = new SwiftInterfaceParser (tokenStream);
var walker = new ParseTreeWalker ();
walker.Walk (this, parser.swiftinterface ());
if (currentElement.Count != 1)
throw new ParseException ("At end of parse, stack should contain precisely one element");
if (module != currentElement.Peek ())
throw new ParseException ("Expected the final element to be the initial module");
LoadReferencedModules ();
PatchPossibleOperators ();
PatchExtensionShortNames ();
PatchExtensionSelfArgs ();
PatchPossibleBadInheritance ();
PatchAssociatedTypeConformance ();
if (typeAliasMap.Count > 0) {
module.Add (new XElement (kTypeAliases, typeAliasMap.ToArray ()));
}
module.Add (new XAttribute (kName, moduleName));
SetLanguageVersion (module);
var tlElement = new XElement ("xamreflect", new XAttribute ("version", "1.0"),
new XElement ("modulelist", module));
var xDocument = new XDocument (new XDeclaration ("1.0", "utf-8", "yes"), tlElement);
return xDocument;
} catch (ParseException) {
throw;
} catch (Exception e) {
throw new ParseException ($"Unknown error parsing {inFile}: {e.Message}", e.InnerException);
}
}
public override void EnterComment ([NotNull] CommentContext context)
{
var commentText = context.GetText ();
InterpretCommentText (commentText);
}
public override void EnterClass_declaration ([NotNull] Class_declarationContext context)
{
var inheritance = GatherInheritance (context.type_inheritance_clause (), forceProtocolInheritance: false);
var attributes = GatherAttributes (context.attributes ());
var isDeprecated = CheckForDeprecated (attributes);
var isUnavailable = CheckForUnavailable (attributes);
var isObjC = AttributesContains (context.attributes (), kObjC);
var accessibility = ToAccess (context.access_level_modifier ());
var isFinal = context.final_clause () != null || accessibility != kOpenCap;
var typeDecl = ToTypeDeclaration (kClass, UnTick (context.class_name ().GetText ()),
accessibility, isObjC, isFinal, isDeprecated, isUnavailable, inheritance, generics: null,
attributes);
var generics = HandleGenerics (context.generic_parameter_clause (), context.generic_where_clause (), false);
if (generics != null)
typeDecl.Add (generics);
currentElement.Push (typeDecl);
}
public override void ExitClass_declaration ([NotNull] Class_declarationContext context)
{
var classElem = currentElement.Pop ();
var givenClassName = classElem.Attribute (kName).Value;
var actualClassName = UnTick (context.class_name ().GetText ());
if (givenClassName != actualClassName)
throw new ParseException ($"class name mismatch on exit declaration: expected {actualClassName} but got {givenClassName}");
AddClassToCurrentElement (classElem);
}
public override void EnterStruct_declaration ([NotNull] Struct_declarationContext context)
{
var inheritance = GatherInheritance (context.type_inheritance_clause (), forceProtocolInheritance: true);
var attributes = GatherAttributes (context.attributes ());
var isDeprecated = CheckForDeprecated (attributes);
var isUnavailable = CheckForUnavailable (attributes);
var isFinal = true; // structs are always final
var isObjC = AttributesContains (context.attributes (), kObjC);
var accessibility = ToAccess (context.access_level_modifier ());
var typeDecl = ToTypeDeclaration (kStruct, UnTick (context.struct_name ().GetText ()),
accessibility, isObjC, isFinal, isDeprecated, isUnavailable, inheritance, generics: null,
attributes);
var generics = HandleGenerics (context.generic_parameter_clause (), context.generic_where_clause (), false);
if (generics != null)
typeDecl.Add (generics);
currentElement.Push (typeDecl);
}
public override void ExitStruct_declaration ([NotNull] Struct_declarationContext context)
{
var structElem = currentElement.Pop ();
var givenStructName = structElem.Attribute (kName).Value;
var actualStructName = UnTick (context.struct_name ().GetText ());
if (givenStructName != actualStructName)
throw new ParseException ($"struct name mismatch on exit declaration: expected {actualStructName} but got {givenStructName}");
AddStructToCurrentElement (structElem);
}
public override void EnterEnum_declaration ([NotNull] Enum_declarationContext context)
{
var inheritanceClause = context.union_style_enum ()?.type_inheritance_clause () ??
context.raw_value_style_enum ()?.type_inheritance_clause ();
var inheritance = GatherInheritance (inheritanceClause, forceProtocolInheritance: true, removeNonProtocols: true);
var attributes = GatherAttributes (context.attributes ());
var isDeprecated = CheckForDeprecated (attributes);
var isUnavailable = CheckForUnavailable (attributes);
var isFinal = true; // enums are always final
var isObjC = AttributesContains (context.attributes (), kObjC);
var accessibility = ToAccess (context.access_level_modifier ());
var typeDecl = ToTypeDeclaration (kEnum, EnumName (context),
accessibility, isObjC, isFinal, isDeprecated, isUnavailable, inheritance, generics: null,
attributes);
var generics = HandleGenerics (EnumGenericParameters (context), EnumGenericWhere (context), false);
if (generics != null)
typeDecl.Add (generics);
currentElement.Push (typeDecl);
}
public override void ExitEnum_declaration ([NotNull] Enum_declarationContext context)
{
var enumElem = currentElement.Pop ();
var givenEnumName = enumElem.Attribute (kName).Value;
var actualEnumName = EnumName (context);
if (givenEnumName != actualEnumName)
throw new ParseException ($"enum name mismatch on exit declaration: expected {actualEnumName} but got {givenEnumName}");
var rawType = GetEnumRawType (context);
if (rawType != null)
enumElem.Add (rawType);
AddEnumToCurrentElement (enumElem);
}
static string EnumName (Enum_declarationContext context)
{
return UnTick (context.union_style_enum () != null ?
context.union_style_enum ().enum_name ().GetText () :
context.raw_value_style_enum ().enum_name ().GetText ());
}
XAttribute GetEnumRawType (Enum_declarationContext context)
{
var alias = EnumTypeAliases (context).FirstOrDefault (ta => ta.typealias_name ().GetText () == kRawValue);
if (alias == null)
return null;
var rawType = alias.typealias_assignment ().type ().GetText ();
return new XAttribute (kRawType, rawType);
}
IEnumerable<Typealias_declarationContext> EnumTypeAliases (Enum_declarationContext context)
{
if (context.union_style_enum () != null)
return UnionTypeAliases (context.union_style_enum ());
else
return RawTypeAliases (context.raw_value_style_enum ());
}
IEnumerable<Typealias_declarationContext> UnionTypeAliases (Union_style_enumContext context)
{
var members = context.union_style_enum_members ();
while (members != null) {
if (members.union_style_enum_member () != null) {
var member = members.union_style_enum_member ();
if (member.nominal_declaration ()?.typealias_declaration () != null)
yield return member.nominal_declaration ().typealias_declaration ();
}
members = members.union_style_enum_members ();
}
yield break;
}
IEnumerable<Typealias_declarationContext> RawTypeAliases (Raw_value_style_enumContext context)
{
var members = context.raw_value_style_enum_members ();
while (members != null) {
if (members.raw_value_style_enum_member () != null) {
var member = members.raw_value_style_enum_member ();
if (member.nominal_declaration ()?.typealias_declaration () != null)
yield return member.nominal_declaration ().typealias_declaration ();
}
members = members.raw_value_style_enum_members ();
}
yield break;
}
public override void EnterRaw_value_style_enum_case_clause ([NotNull] Raw_value_style_enum_case_clauseContext context)
{
var enumElements = new XElement (kElements);
foreach (var enumCase in RawCases (context.raw_value_style_enum_case_list ())) {
var enumElement = ToRawEnumElement (enumCase);
enumElements.Add (enumElement);
}
AddEnumNonEmptyElements (enumElements);
}
public override void EnterUnion_style_enum_case_clause ([NotNull] Union_style_enum_case_clauseContext context)
{
var enumElements = new XElement (kElements);
foreach (var enumCase in UnionCases (context.union_style_enum_case_list ())) {
var enumElement = ToUnionEnumElement (enumCase);
enumElements.Add (enumElement);
}
AddEnumNonEmptyElements (enumElements);
}
void AddEnumNonEmptyElements (XElement enumElements)
{
if (enumElements.HasElements) {
var currentEnum = currentElement.Peek ();
if (currentEnum.Attribute (kKind)?.Value != kEnum)
throw new ParseException ("Current element needs to be an enum");
var existingElements = currentEnum.Element (kElements);
if (existingElements != null) {
foreach (var elem in enumElements.Elements ()) {
existingElements.Add (elem);
}
} else {
currentEnum.Add (enumElements);
}
}
}
IEnumerable<Raw_value_style_enum_caseContext> RawCases (Raw_value_style_enum_case_listContext context)
{
while (context != null) {
if (context.raw_value_style_enum_case () != null) {
yield return context.raw_value_style_enum_case ();
}
context = context.raw_value_style_enum_case_list ();
}
yield break;
}
XElement ToRawEnumElement (Raw_value_style_enum_caseContext context)
{
var enumElem = new XElement (kElement, new XAttribute (kName, UnTick (context.enum_case_name ().GetText ())));
var value = context.raw_value_assignment ();
if (value != null)
enumElem.Add (new XAttribute (kIntValue, value.raw_value_literal ().GetText ()));
return enumElem;
}
IEnumerable<Union_style_enum_caseContext> UnionCases (Union_style_enum_case_listContext context)
{
while (context != null) {
if (context.union_style_enum_case () != null) {
yield return context.union_style_enum_case ();
}
context = context.union_style_enum_case_list ();
}
yield break;
}
XElement ToUnionEnumElement (Union_style_enum_caseContext context)
{
var enumElement = new XElement (kElement, new XAttribute (kName, UnTick (context.enum_case_name ().GetText ())));
if (context.tuple_type () != null) {
var tupString = context.tuple_type ().GetText ();
// special casing:
// the type of a union case is a tuple, but we special case
// unit tuples to be just the type of the unit
// which may be something like ((((((()))))))
// in which case we want to let it come through as is.
// a unit tuple may also have a type label which we don't care
// about so make that go away too.
if (tupString.IndexOf (',') < 0 && tupString.IndexOf (':') < 0) {
var pastLastOpen = tupString.LastIndexOf ('(') + 1;
var firstClosed = tupString.IndexOf (')');
if (pastLastOpen != firstClosed) {
tupString = tupString.Substring (pastLastOpen, firstClosed - pastLastOpen);
var colonIndex = tupString.IndexOf (':');
if (colonIndex >= 0) {
tupString = tupString.Substring (colonIndex + 1);
}
}
}
enumElement.Add (new XAttribute (kType, tupString));
}
return enumElement;
}
public override void EnterProtocol_declaration ([NotNull] Protocol_declarationContext context)
{
var inheritance = GatherInheritance (context.type_inheritance_clause (), forceProtocolInheritance: true);
var attributes = GatherAttributes (context.attributes ());
var isDeprecated = CheckForDeprecated (attributes);
var isUnavailable = CheckForUnavailable (attributes);
var isFinal = true; // protocols don't have final
var isObjC = AttributesContains (context.attributes (), kObjC);
var accessibility = ToAccess (context.access_level_modifier ());
var typeDecl = ToTypeDeclaration (kProtocol, UnTick (context.protocol_name ().GetText ()),
accessibility, isObjC, isFinal, isDeprecated, isUnavailable, inheritance, generics: null,
attributes);
currentElement.Push (typeDecl);
}
public override void ExitProtocol_declaration ([NotNull] Protocol_declarationContext context)
{
var protocolElem = currentElement.Pop ();
var givenProtocolName = protocolElem.Attribute (kName).Value;
var actualProtocolName = UnTick (context.protocol_name ().GetText ());
if (givenProtocolName != actualProtocolName)
throw new ParseException ($"protocol name mismatch on exit declaration: expected {actualProtocolName} but got {givenProtocolName}");
if (currentElement.Peek ().Name != kModule)
throw new ParseException ($"Expected a module on the element stack but found {currentElement.Peek ()}");
currentElement.Peek ().Add (protocolElem);
}
public override void EnterProtocol_associated_type_declaration ([NotNull] Protocol_associated_type_declarationContext context)
{
var conformingProtocols = GatherConformingProtocols (context.type_inheritance_clause ());
var defaultDefn = context.typealias_assignment ()?.type ().GetText ();
var assocType = new XElement (kAssociatedType,
new XAttribute (kName, UnTick (context.typealias_name ().GetText ())));
if (defaultDefn != null)
assocType.Add (new XAttribute (kDefaultType, UnTick (defaultDefn)));
if (conformingProtocols != null && conformingProtocols.Count > 0) {
var confomingElem = new XElement (kConformingProtocols, conformingProtocols.ToArray ());
assocType.Add (confomingElem);
associatedTypesWithConformance.Add (assocType);
}
AddAssociatedTypeToCurrentElement (assocType);
}
List<XElement> GatherConformingProtocols (Type_inheritance_clauseContext context)
{
if (context == null)
return null;
var elems = new List<XElement> ();
if (context.class_requirement () != null) {
// not sure what to do here
// this is just the keyword 'class'
}
var inheritance = context.type_inheritance_list ();
while (inheritance != null) {
var elem = inheritance.GetText ();
var name = inheritance.type_identifier ()?.GetText ();
if (name != null)
elems.Add (new XElement (kConformingProtocol, new XAttribute (kName, UnTick (name))));
inheritance = inheritance.type_inheritance_list ();
}
return elems;
}
static Generic_parameter_clauseContext EnumGenericParameters (Enum_declarationContext context)
{
return context.union_style_enum ()?.generic_parameter_clause () ??
context.raw_value_style_enum ()?.generic_parameter_clause ();
}
static Generic_where_clauseContext EnumGenericWhere (Enum_declarationContext context)
{
return context.union_style_enum ()?.generic_where_clause () ??
context.raw_value_style_enum ()?.generic_where_clause ();
}
public override void EnterFunction_declaration ([NotNull] Function_declarationContext context)
{
var head = context.function_head ();
var signature = context.function_signature ();
var name = UnTick (context.function_name ().GetText ());
var returnType = signature.function_result () != null ? signature.function_result ().type ().GetText () : "()";
var accessibility = AccessibilityFromModifiers (head.declaration_modifiers ());
var isStatic = IsStaticOrClass (head.declaration_modifiers ());
var hasThrows = signature.throws_clause () != null || signature.rethrows_clause () != null;
var isFinal = ModifiersContains (head.declaration_modifiers (), kFinal);
var isOptional = ModifiersContains (head.declaration_modifiers (), kOptional);
var isConvenienceInit = false;
var operatorKind = kNone;
var isMutating = ModifiersContains (head.declaration_modifiers (), kMutating);
var isRequired = ModifiersContains (head.declaration_modifiers (), kRequired);
var isProperty = false;
var attributes = GatherAttributes (head.attributes ());
var isDeprecated = CheckForDeprecated (attributes);
var isUnavailable = CheckForUnavailable (attributes);
var isAsync = signature.async_clause () != null;
var functionDecl = ToFunctionDeclaration (name, returnType, accessibility, isStatic, hasThrows,
isFinal, isOptional, isConvenienceInit, objCSelector: null, operatorKind,
isDeprecated, isUnavailable, isMutating, isRequired, isProperty, isAsync, attributes);
var generics = HandleGenerics (context.generic_parameter_clause (), context.generic_where_clause (), true);
if (generics != null)
functionDecl.Add (generics);
functions.Add (new Tuple<Function_declarationContext, XElement> (context, functionDecl));
currentElement.Push (functionDecl);
}
public override void ExitFunction_declaration ([NotNull] Function_declarationContext context)
{
ExitFunctionWithName (UnTick (context.function_name ().GetText ()));
}
void ExitFunctionWithName (string expectedName)
{
var functionDecl = currentElement.Pop ();
if (functionDecl.Name != kFunc)
throw new ParseException ($"Expected a func node but got a {functionDecl.Name}");
var givenName = functionDecl.Attribute (kName);
if (givenName == null)
throw new ParseException ("func node doesn't have a name element");
if (givenName.Value != expectedName)
throw new ParseException ($"Expected a func node with name {expectedName} but got {givenName.Value}");
AddObjCSelector (functionDecl);
AddElementToParentMembers (functionDecl);
}
void AddObjCSelector (XElement functionDecl)
{
var selectorFactory = new ObjCSelectorFactory (functionDecl);
var selector = selectorFactory.Generate ();
if (!String.IsNullOrEmpty (selector)) {
functionDecl.Add (new XAttribute (kObjCSelector, selector));
}
}
XElement PeekAsFunction ()
{
var functionDecl = currentElement.Peek ();
if (functionDecl.Name != kFunc)
throw new ParseException ($"Expected a func node but got a {functionDecl.Name}");
return functionDecl;
}
void AddElementToParentMembers (XElement elem)
{
var parent = currentElement.Peek ();
if (parent.Name == kModule) {
parent.Add (elem);
return;
}
var memberElem = GetOrCreate (parent, kMembers);
memberElem.Add (elem);
}
bool IsInInstance ()
{
var parent = currentElement.Peek ();
return parent.Name != kModule;
}
bool HasObjCElement (XElement elem)
{
var objcAttr = elem.Descendants ()
.FirstOrDefault (el => el.Name == kAttribute && el.Attribute ("name")?.Value == kObjC);
return objcAttr != null;
}
public override void EnterInitializer_declaration ([NotNull] Initializer_declarationContext context)
{
var head = context.initializer_head ();
var name = kDotCtor;
// may be optional, otherwise return type is the instance type
var returnType = GetInstanceName () + (head.OpQuestion () != null ? "?" : "");
var accessibility = AccessibilityFromModifiers (head.declaration_modifiers ());
var isStatic = true;
var hasThrows = context.throws_clause () != null || context.rethrows_clause () != null;
var isFinal = ModifiersContains (head.declaration_modifiers (), kFinal);
var isOptional = ModifiersContains (head.declaration_modifiers (), kOptional);
var isConvenienceInit = ModifiersContains (head.declaration_modifiers (), kConvenience);
var operatorKind = kNone;
var attributes = GatherAttributes (head.attributes ());
var isDeprecated = CheckForDeprecated (attributes);
var isUnavailable = CheckForUnavailable (attributes);
var isMutating = ModifiersContains (head.declaration_modifiers (), kMutating);
var isRequired = ModifiersContains (head.declaration_modifiers (), kRequired);
var isProperty = false;
var functionDecl = ToFunctionDeclaration (name, returnType, accessibility, isStatic, hasThrows,
isFinal, isOptional, isConvenienceInit, objCSelector: null, operatorKind,
isDeprecated, isUnavailable, isMutating, isRequired, isProperty,
isAsync: false, attributes);
currentElement.Push (functionDecl);
}
public override void ExitInitializer_declaration ([NotNull] Initializer_declarationContext context)
{
ExitFunctionWithName (kDotCtor);
}
public override void EnterDeinitializer_declaration ([NotNull] Deinitializer_declarationContext context)
{
var name = kDotDtor;
var returnType = "()";
// this might have to be forced to public, otherwise deinit is always internal, which it
// decidedly is NOT.
var accessibility = kPublic;
var isStatic = false;
var hasThrows = false;
var isFinal = ModifiersContains (context.declaration_modifiers (), kFinal);
var isOptional = ModifiersContains (context.declaration_modifiers (), kOptional);
var isConvenienceInit = false;
var operatorKind = kNone;
var attributes = GatherAttributes (context.attributes ());
var isDeprecated = CheckForDeprecated (attributes);
var isUnavailable = CheckForUnavailable (attributes);
var isMutating = ModifiersContains (context.declaration_modifiers (), kMutating);
var isRequired = ModifiersContains (context.declaration_modifiers (), kRequired);
var isProperty = false;
var functionDecl = ToFunctionDeclaration (name, returnType, accessibility, isStatic, hasThrows,
isFinal, isOptional, isConvenienceInit, objCSelector: null, operatorKind,
isDeprecated, isUnavailable, isMutating, isRequired, isProperty, isAsync: false, attributes);
// always has two parameter lists: (instance)()
currentElement.Push (functionDecl);
var parameterLists = new XElement (kParameterLists, MakeInstanceParameterList ());
currentElement.Pop ();
parameterLists.Add (new XElement (kParameterList, new XAttribute (kIndex, "1")));
functionDecl.Add (parameterLists);
currentElement.Push (functionDecl);
}
public override void ExitDeinitializer_declaration ([NotNull] Deinitializer_declarationContext context)
{
ExitFunctionWithName (kDotDtor);
}
public override void EnterSubscript_declaration ([NotNull] Subscript_declarationContext context)
{
// subscripts are...funny.
// They have one parameter list but expand out to two function declarations
// To handle this, we process the parameter list here for the getter
// If there's a setter, we make one of those too.
// Then since we're effectively done, we push a special XElement on the stack
// named IGNORE which will make the parameter list event handler exit.
// On ExitSubscript_declaration, we remove the IGNORE tag
var head = context.subscript_head ();
var resultType = context.subscript_result ().type ().GetText ();
var accessibility = AccessibilityFromModifiers (head.declaration_modifiers ());
var attributes = GatherAttributes (head.attributes ());
var isDeprecated = CheckForDeprecated (attributes);
var isUnavailable = CheckForUnavailable (attributes);
var isStatic = false;
var hasThrows = false;
var isAsync = HasAsync (context.getter_setter_keyword_block ()?.getter_keyword_clause ());
var isFinal = ModifiersContains (head.declaration_modifiers (), kFinal);
var isOptional = ModifiersContains (head.declaration_modifiers (), kOptional);
var isMutating = ModifiersContains (head.declaration_modifiers (), kMutating);
var isRequired = ModifiersContains (head.declaration_modifiers (), kRequired);
var isProperty = true;
var getParamList = MakeParameterList (head.parameter_clause ().parameter_list (), 1, true);
var getFunc = ToFunctionDeclaration (kGetSubscript, resultType, accessibility, isStatic, hasThrows,
isFinal, isOptional, isConvenienceInit: false, objCSelector: null, kNone,
isDeprecated, isUnavailable, isMutating, isRequired, isProperty, isAsync: isAsync, attributes);
currentElement.Push (getFunc);
var getParamLists = new XElement (kParameterLists, MakeInstanceParameterList (), getParamList);
currentElement.Pop ();
getFunc.Add (getParamLists);
AddObjCSelector (getFunc);
AddElementToParentMembers (getFunc);
var setParamList = context.getter_setter_keyword_block ()?.setter_keyword_clause () != null
? MakeParameterList (head.parameter_clause ().parameter_list (), 1, true, startIndex: 1) : null;
if (setParamList != null) {
var index = 0;
var parmName = context.getter_setter_keyword_block ().setter_keyword_clause ().new_value_name ()?.GetText ()
?? kNewValue;
var newValueParam = new XElement (kParameter, new XAttribute (nameof (index), index.ToString ()),
new XAttribute (kType, resultType), new XAttribute (kPublicName, ""),
new XAttribute (kPrivateName, parmName), new XAttribute (kIsVariadic, false));
setParamList.AddFirst (newValueParam);
var setFunc = ToFunctionDeclaration (kSetSubscript, "()", accessibility, isStatic, hasThrows,
isFinal, isOptional, isConvenienceInit: false, objCSelector: null, kNone,
isDeprecated, isUnavailable, isMutating, isRequired, isProperty, isAsync: false, attributes);
currentElement.Push (setFunc);
var setParamLists = new XElement (kParameterLists, MakeInstanceParameterList (), setParamList);
currentElement.Pop ();
setFunc.Add (setParamLists);
AddObjCSelector (setFunc);
AddElementToParentMembers (setFunc);
}
// this makes the subscript parameter list get ignored because we already handled it.
PushIgnore ();
}
public override void ExitSubscript_declaration ([NotNull] Subscript_declarationContext context)
{
PopIgnore ();
}
public override void EnterVariable_declaration ([NotNull] Variable_declarationContext context)
{
var head = context.variable_declaration_head ();
var accessibility = AccessibilityFromModifiers (head.declaration_modifiers ());
var attributes = GatherAttributes (head.attributes ());
var isDeprecated = CheckForDeprecated (attributes);
var isUnavailable = CheckForUnavailable (attributes);
var isStatic = ModifiersContains (head.declaration_modifiers (), kStatic);
var isFinal = ModifiersContains (head.declaration_modifiers (), kFinal);
var isLet = head.let_clause () != null;
var isOptional = ModifiersContains (head.declaration_modifiers (), kOptional);
var isMutating = ModifiersContains (head.declaration_modifiers (), kMutating);
var isRequired = ModifiersContains (head.declaration_modifiers (), kRequired);
var isProperty = true;
foreach (var tail in context.variable_declaration_tail ()) {
var name = UnTick (tail.variable_name ().GetText ());
var resultType = TrimColon (tail.type_annotation ().GetText ());
var hasThrows = false;
var isAsync = HasAsync (tail.getter_setter_keyword_block ()?.getter_keyword_clause ());
var getParamList = new XElement (kParameterList, new XAttribute (kIndex, "1"));
var getFunc = ToFunctionDeclaration ("get_" + name,
resultType, accessibility, isStatic, hasThrows, isFinal, isOptional,
isConvenienceInit: false, objCSelector: null, operatorKind: kNone, isDeprecated,
isUnavailable, isMutating, isRequired, isProperty, isAsync: isAsync, attributes);
currentElement.Push (getFunc);
var getParamLists = new XElement (kParameterLists, MakeInstanceParameterList (), getParamList);
currentElement.Pop ();
getFunc.Add (getParamLists);
AddElementToParentMembers (getFunc);
AddObjCSelector (getFunc);
var setParamList = HasSetter (tail, isLet) ?
new XElement (kParameterList, new XAttribute (kIndex, "1")) : null;
if (setParamList != null) {
var parmName = tail.getter_setter_keyword_block ()?.setter_keyword_clause ().new_value_name ()?.GetText ()
?? kNewValue;
var setterType = EscapePossibleClosureType (resultType);
var newValueParam = new XElement (kParameter, new XAttribute (kIndex, "0"),
new XAttribute (kType, setterType), new XAttribute (kPublicName, parmName),
new XAttribute (kPrivateName, parmName), new XAttribute (kIsVariadic, false));
setParamList.Add (newValueParam);
var setFunc = ToFunctionDeclaration ("set_" + name,
"()", accessibility, isStatic, hasThrows, isFinal, isOptional,
isConvenienceInit: false, objCSelector: null, operatorKind: kNone, isDeprecated,
isUnavailable, isMutating, isRequired, isProperty, isAsync: false, attributes);
currentElement.Push (setFunc);
var setParamLists = new XElement (kParameterLists, MakeInstanceParameterList (), setParamList);
currentElement.Pop ();
setFunc.Add (setParamLists);
AddElementToParentMembers (setFunc);
AddObjCSelector (setFunc);
}
var prop = new XElement (kProperty, new XAttribute (kName, name),
new XAttribute (nameof (accessibility), accessibility),
new XAttribute (kType, resultType),
new XAttribute (kStorage, kComputed),
new XAttribute (nameof (isStatic), XmlBool (isStatic)),
new XAttribute (nameof (isLet), XmlBool (isLet)),
new XAttribute (nameof (isDeprecated), XmlBool (isDeprecated)),
new XAttribute (nameof (isUnavailable), XmlBool (isUnavailable)),
new XAttribute (nameof (isOptional), XmlBool (isOptional)));
AddElementToParentMembers (prop);
}
PushIgnore ();
}
bool HasSetter (Variable_declaration_tailContext context, bool isLet)
{
// conditions for having a setter:
// getter_setter_keyword_block is null (public var foo: Type)
// getter_setter_keyword_block is non-null and the getter_setter_keyword_block
// has a non-null setter_keyword_clause (public var foo:Type { get; set; }, public foo: Type { set }
return !isLet && (context.getter_setter_keyword_block () == null ||
context.getter_setter_keyword_block ().setter_keyword_clause () != null);
}
public override void EnterExtension_declaration ([NotNull] Extension_declarationContext context)
{
var onType = UnTick (context.type_identifier ().GetText ());
var inherits = GatherInheritance (context.type_inheritance_clause (), forceProtocolInheritance: true);
// why, you say, why put a kKind tag into an extension?
// The reason is simple: this is a hack. Most of the contents
// of an extension are the same as a class and as a result we can
// pretend that it's a class and everything will work to fill it out
// using the class/struct/enum code for members.
var extensionElem = new XElement (kExtension,
new XAttribute (nameof (onType), onType),
new XAttribute (kKind, kClass));
if (inherits?.Count > 0)
extensionElem.Add (new XElement (nameof (inherits), inherits.ToArray ()));
currentElement.Push (extensionElem);
extensions.Add (extensionElem);
}
public override void ExitExtension_declaration ([NotNull] Extension_declarationContext context)
{
var extensionElem = currentElement.Pop ();
var onType = extensionElem.Attribute (kOnType);
var givenOnType = onType.Value;
var actualOnType = UnTick (context.type_identifier ().GetText ());
if (givenOnType != actualOnType)
throw new Exception ($"extension type mismatch on exit declaration: expected {actualOnType} but got {givenOnType}");
// remove the kKind attribute - you've done your job.
extensionElem.Attribute (kKind)?.Remove ();
currentElement.Peek ().Add (extensionElem);
}
public override void ExitImport_statement ([NotNull] Import_statementContext context)
{
// this is something like: import class Foo.Bar
// and we're not handling that yet
if (context.import_kind () != null)
return;
importModules.Add (context.import_path ().GetText ());
}
public override void EnterOperator_declaration ([NotNull] Operator_declarationContext context)
{
var operatorElement = InfixOperator (context.infix_operator_declaration ())
?? PostfixOperator (context.postfix_operator_declaration ())
?? PrefixOperator (context.prefix_operator_declaration ());
operators.Add (operatorElement);
currentElement.Peek ().Add (operatorElement);
}
public override void EnterOptional_type ([NotNull] Optional_typeContext context)
{
var innerType = context.type ().GetText ();
}
XElement InfixOperator (Infix_operator_declarationContext context)
{
if (context == null)
return null;
return GeneralOperator (kInfix, context.@operator (),
context.infix_operator_group ()?.precedence_group_name ()?.GetText () ?? "");
}
XElement PostfixOperator (Postfix_operator_declarationContext context)
{
if (context == null)
return null;
return GeneralOperator (kPostfix, context.@operator (), "");
}
XElement PrefixOperator (Prefix_operator_declarationContext context)
{
if (context == null)
return null;
return GeneralOperator (kPrefix, context.@operator (), "");
}
XElement GeneralOperator (string operatorKind, OperatorContext context, string precedenceGroup)
{
return new XElement (kOperator,
new XAttribute (kName, context.Operator ().GetText ()),
new XAttribute (nameof (operatorKind), operatorKind),
new XAttribute (nameof (precedenceGroup), precedenceGroup));
}
XElement HandleGenerics (Generic_parameter_clauseContext genericContext, Generic_where_clauseContext whereContext, bool addParentGenerics)
{
if (genericContext == null)
return null;
var genericElem = new XElement (kGenericParameters);
if (addParentGenerics)
AddParentGenerics (genericElem);
foreach (var generic in genericContext.generic_parameter_list ().generic_parameter ()) {
var name = UnTick (generic.type_name ().GetText ());
var genParam = new XElement (kParam, new XAttribute (kName, name));
genericElem.Add (genParam);
var whereType = generic.type_identifier ()?.GetText () ??
generic.protocol_composition_type ()?.GetText ();
if (whereType != null) {
genericElem.Add (MakeConformanceWhere (name, whereType));
}
}
if (whereContext == null)
return genericElem;
foreach (var requirement in whereContext.requirement_list ().requirement ()) {
if (requirement.conformance_requirement () != null) {
var name = UnTick (requirement.conformance_requirement ().type_identifier () [0].GetText ());
// if there is no protocol composition type, then it's the second type identifier
var from = requirement.conformance_requirement ().protocol_composition_type ()?.GetText ()
?? requirement.conformance_requirement ().type_identifier () [1].GetText ();
genericElem.Add (MakeConformanceWhere (name, from));
} else {
var name = UnTick (requirement.same_type_requirement ().type_identifier ().GetText ());
var type = requirement.same_type_requirement ().type ().GetText ();
genericElem.Add (MakeEqualityWhere (name, type));
}
}
return genericElem;
}
public override void ExitTypealias_declaration ([NotNull] Typealias_declarationContext context)
{
var name = UnTick (context.typealias_name ().GetText ());
var generics = context.generic_parameter_clause ()?.GetText () ?? "";
var targetType = context.typealias_assignment ().type ().GetText ();
var access = ToAccess (context.access_level_modifier ());