forked from swiftwasm/JavaScriptKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExportSwift.swift
More file actions
1662 lines (1507 loc) · 68.2 KB
/
ExportSwift.swift
File metadata and controls
1662 lines (1507 loc) · 68.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
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
import SwiftBasicFormat
import SwiftSyntax
import SwiftSyntaxBuilder
#if canImport(BridgeJSSkeleton)
import BridgeJSSkeleton
#endif
#if canImport(BridgeJSUtilities)
import BridgeJSUtilities
#endif
/// Exports Swift functions and classes to JavaScript
///
/// This class processes Swift source files to find declarations marked with `@JS`
/// and generates:
/// 1. Swift glue code to call the Swift functions from JavaScript
/// 2. Skeleton files that define the structure of the exported APIs
///
/// The generated skeletons will be used by ``BridgeJSLink`` to generate
/// JavaScript glue code and TypeScript definitions.
public class ExportSwift {
let progress: ProgressReporting
let moduleName: String
private var exportedFunctions: [ExportedFunction] = []
private var exportedClasses: [ExportedClass] = []
private var exportedEnums: [ExportedEnum] = []
private var typeDeclResolver: TypeDeclResolver = TypeDeclResolver()
private let enumCodegen: EnumCodegen = EnumCodegen()
public init(progress: ProgressReporting, moduleName: String) {
self.progress = progress
self.moduleName = moduleName
}
/// Processes a Swift source file to find declarations marked with @JS
///
/// - Parameters:
/// - sourceFile: The parsed Swift source file to process
/// - inputFilePath: The file path for error reporting
public func addSourceFile(_ sourceFile: SourceFileSyntax, _ inputFilePath: String) throws {
progress.print("Processing \(inputFilePath)")
typeDeclResolver.addSourceFile(sourceFile)
let errors = try parseSingleFile(sourceFile)
if errors.count > 0 {
throw BridgeJSCoreError(
errors.map { $0.formattedDescription(fileName: inputFilePath) }
.joined(separator: "\n")
)
}
}
/// Finalizes the export process and generates the bridge code
///
/// - Returns: A tuple containing the generated Swift code and a skeleton
/// describing the exported APIs
public func finalize() throws -> (outputSwift: String, outputSkeleton: ExportedSkeleton)? {
guard let outputSwift = try renderSwiftGlue() else {
return nil
}
return (
outputSwift: outputSwift,
outputSkeleton: ExportedSkeleton(
moduleName: moduleName,
functions: exportedFunctions,
classes: exportedClasses,
enums: exportedEnums
)
)
}
fileprivate final class APICollector: SyntaxAnyVisitor {
var exportedFunctions: [ExportedFunction] = []
/// The names of the exported classes, in the order they were written in the source file
var exportedClassNames: [String] = []
var exportedClassByName: [String: ExportedClass] = [:]
/// The names of the exported enums, in the order they were written in the source file
var exportedEnumNames: [String] = []
var exportedEnumByName: [String: ExportedEnum] = [:]
var errors: [DiagnosticError] = []
/// Creates a unique key for a class by combining name and namespace
private func classKey(name: String, namespace: [String]?) -> String {
if let namespace = namespace, !namespace.isEmpty {
return "\(namespace.joined(separator: ".")).\(name)"
} else {
return name
}
}
/// Temporary storage for enum data during visitor traversal since EnumCaseDeclSyntax lacks parent context
struct CurrentEnum {
var name: String?
var cases: [EnumCase] = []
var rawType: String?
}
var currentEnum = CurrentEnum()
enum State {
case topLevel
case classBody(name: String, key: String)
case enumBody(name: String)
}
struct StateStack {
private var states: [State]
var current: State {
return states.last!
}
init(_ initialState: State) {
self.states = [initialState]
}
mutating func push(state: State) {
states.append(state)
}
mutating func pop() {
_ = states.removeLast()
}
}
var stateStack: StateStack = StateStack(.topLevel)
var state: State {
return stateStack.current
}
let parent: ExportSwift
init(parent: ExportSwift) {
self.parent = parent
super.init(viewMode: .sourceAccurate)
}
private func diagnose(node: some SyntaxProtocol, message: String, hint: String? = nil) {
errors.append(DiagnosticError(node: node, message: message, hint: hint))
}
private func diagnoseUnsupportedType(node: some SyntaxProtocol, type: String) {
diagnose(
node: node,
message: "Unsupported type: \(type)",
hint: "Only primitive types and types defined in the same module are allowed"
)
}
private func diagnoseNestedOptional(node: some SyntaxProtocol, type: String) {
diagnose(
node: node,
message: "Nested optional types are not supported: \(type)",
hint: "Use a single optional like String? instead of String?? or Optional<Optional<T>>"
)
}
override func visit(_ node: FunctionDeclSyntax) -> SyntaxVisitorContinueKind {
switch state {
case .topLevel:
if let exportedFunction = visitFunction(
node: node
) {
exportedFunctions.append(exportedFunction)
}
return .skipChildren
case .classBody(_, let classKey):
if let exportedFunction = visitFunction(
node: node
) {
exportedClassByName[classKey]?.methods.append(exportedFunction)
}
return .skipChildren
case .enumBody:
diagnose(node: node, message: "Functions are not supported inside enums")
return .skipChildren
}
}
private func visitFunction(node: FunctionDeclSyntax) -> ExportedFunction? {
guard let jsAttribute = node.attributes.firstJSAttribute else {
return nil
}
let name = node.name.text
let namespace = extractNamespace(from: jsAttribute)
if namespace != nil, case .classBody = state {
diagnose(
node: jsAttribute,
message: "Namespace is only needed in top-level declaration",
hint: "Remove the namespace from @JS attribute or move this function to top-level"
)
}
var parameters: [Parameter] = []
for param in node.signature.parameterClause.parameters {
let resolvedType = self.parent.lookupType(for: param.type)
if let type = resolvedType, case .optional(let wrappedType) = type, wrappedType.isOptional {
diagnoseNestedOptional(node: param.type, type: param.type.trimmedDescription)
continue
}
guard let type = resolvedType else {
diagnoseUnsupportedType(node: param.type, type: param.type.trimmedDescription)
continue
}
let name = param.secondName?.text ?? param.firstName.text
let label = param.firstName.text
parameters.append(Parameter(label: label, name: name, type: type))
}
let returnType: BridgeType
if let returnClause = node.signature.returnClause {
let resolvedType = self.parent.lookupType(for: returnClause.type)
if let type = resolvedType, case .optional(let wrappedType) = type, wrappedType.isOptional {
diagnoseNestedOptional(node: returnClause.type, type: returnClause.type.trimmedDescription)
return nil
}
guard let type = resolvedType else {
diagnoseUnsupportedType(node: returnClause.type, type: returnClause.type.trimmedDescription)
return nil
}
returnType = type
} else {
returnType = .void
}
let abiName: String
switch state {
case .topLevel:
abiName = "bjs_\(name)"
case .classBody(let className, _):
abiName = "bjs_\(className)_\(name)"
case .enumBody:
abiName = ""
diagnose(
node: node,
message: "Functions are not supported inside enums"
)
}
guard let effects = collectEffects(signature: node.signature) else {
return nil
}
return ExportedFunction(
name: name,
abiName: abiName,
parameters: parameters,
returnType: returnType,
effects: effects,
namespace: namespace
)
}
private func collectEffects(signature: FunctionSignatureSyntax) -> Effects? {
let isAsync = signature.effectSpecifiers?.asyncSpecifier != nil
var isThrows = false
if let throwsClause: ThrowsClauseSyntax = signature.effectSpecifiers?.throwsClause {
// Limit the thrown type to JSException for now
guard let thrownType = throwsClause.type else {
diagnose(
node: throwsClause,
message: "Thrown type is not specified, only JSException is supported for now"
)
return nil
}
guard thrownType.trimmedDescription == "JSException" else {
diagnose(
node: throwsClause,
message: "Only JSException is supported for thrown type, got \(thrownType.trimmedDescription)"
)
return nil
}
isThrows = true
}
return Effects(isAsync: isAsync, isThrows: isThrows)
}
private func extractNamespace(
from jsAttribute: AttributeSyntax
) -> [String]? {
guard let arguments = jsAttribute.arguments?.as(LabeledExprListSyntax.self) else {
return nil
}
guard let namespaceArg = arguments.first(where: { $0.label?.text == "namespace" }),
let stringLiteral = namespaceArg.expression.as(StringLiteralExprSyntax.self),
let namespaceString = stringLiteral.segments.first?.as(StringSegmentSyntax.self)?.content.text
else {
return nil
}
return namespaceString.split(separator: ".").map(String.init)
}
private func extractEnumStyle(
from jsAttribute: AttributeSyntax
) -> EnumEmitStyle? {
guard let arguments = jsAttribute.arguments?.as(LabeledExprListSyntax.self),
let styleArg = arguments.first(where: { $0.label?.text == "enumStyle" })
else {
return nil
}
let text = styleArg.expression.trimmedDescription
if text.contains("tsEnum") {
return .tsEnum
}
if text.contains("const") {
return .const
}
return nil
}
override func visit(_ node: InitializerDeclSyntax) -> SyntaxVisitorContinueKind {
guard node.attributes.hasJSAttribute() else { return .skipChildren }
guard case .classBody(let className, _) = state else {
if case .enumBody(_) = state {
diagnose(node: node, message: "Initializers are not supported inside enums")
} else {
diagnose(node: node, message: "@JS init must be inside a @JS class")
}
return .skipChildren
}
if let jsAttribute = node.attributes.firstJSAttribute,
extractNamespace(from: jsAttribute) != nil
{
diagnose(
node: jsAttribute,
message: "Namespace is not supported for initializer declarations",
hint: "Remove the namespace from @JS attribute"
)
}
var parameters: [Parameter] = []
for param in node.signature.parameterClause.parameters {
guard let type = self.parent.lookupType(for: param.type) else {
diagnoseUnsupportedType(node: param.type, type: param.type.trimmedDescription)
continue
}
let name = param.secondName?.text ?? param.firstName.text
let label = param.firstName.text
parameters.append(Parameter(label: label, name: name, type: type))
}
guard let effects = collectEffects(signature: node.signature) else {
return .skipChildren
}
let constructor = ExportedConstructor(
abiName: "bjs_\(className)_init",
parameters: parameters,
effects: effects
)
if case .classBody(_, let classKey) = state {
exportedClassByName[classKey]?.constructor = constructor
}
return .skipChildren
}
override func visit(_ node: VariableDeclSyntax) -> SyntaxVisitorContinueKind {
guard node.attributes.hasJSAttribute() else { return .skipChildren }
guard case .classBody(_, let classKey) = state else {
diagnose(node: node, message: "@JS var must be inside a @JS class")
return .skipChildren
}
if let jsAttribute = node.attributes.firstJSAttribute,
extractNamespace(from: jsAttribute) != nil
{
diagnose(
node: jsAttribute,
message: "Namespace is not supported for property declarations",
hint: "Remove the namespace from @JS attribute"
)
}
// Process each binding (variable declaration)
for binding in node.bindings {
guard let pattern = binding.pattern.as(IdentifierPatternSyntax.self) else {
diagnose(node: binding.pattern, message: "Complex patterns not supported for @JS properties")
continue
}
let propertyName = pattern.identifier.text
guard let typeAnnotation = binding.typeAnnotation else {
diagnose(node: binding, message: "@JS property must have explicit type annotation")
continue
}
guard let propertyType = self.parent.lookupType(for: typeAnnotation.type) else {
diagnoseUnsupportedType(node: typeAnnotation.type, type: typeAnnotation.type.trimmedDescription)
continue
}
// Check if property is readonly
let isLet = node.bindingSpecifier.tokenKind == .keyword(.let)
let isGetterOnly = node.bindings.contains(where: {
switch $0.accessorBlock?.accessors {
case .accessors(let accessors):
// Has accessors - check if it only has a getter (no setter, willSet, or didSet)
return !accessors.contains(where: { accessor in
let tokenKind = accessor.accessorSpecifier.tokenKind
return tokenKind == .keyword(.set) || tokenKind == .keyword(.willSet)
|| tokenKind == .keyword(.didSet)
})
case .getter:
// Has only a getter block
return true
case nil:
// No accessor block - this is a stored property, not readonly
return false
}
})
let isReadonly = isLet || isGetterOnly
let exportedProperty = ExportedProperty(
name: propertyName,
type: propertyType,
isReadonly: isReadonly
)
exportedClassByName[classKey]?.properties.append(exportedProperty)
}
return .skipChildren
}
override func visit(_ node: ClassDeclSyntax) -> SyntaxVisitorContinueKind {
let name = node.name.text
guard let jsAttribute = node.attributes.firstJSAttribute else {
return .skipChildren
}
let attributeNamespace = extractNamespace(from: jsAttribute)
let computedNamespace = computeNamespace(for: node)
if computedNamespace != nil && attributeNamespace != nil {
diagnose(
node: jsAttribute,
message: "Nested classes cannot specify their own namespace",
hint: "Remove the namespace from @JS attribute - nested classes inherit namespace from parent"
)
return .skipChildren
}
let effectiveNamespace = computedNamespace ?? attributeNamespace
let swiftCallName = ExportSwift.computeSwiftCallName(for: node, itemName: name)
let explicitAccessControl = computeExplicitAtLeastInternalAccessControl(
for: node,
message: "Class visibility must be at least internal"
)
let exportedClass = ExportedClass(
name: name,
swiftCallName: swiftCallName,
explicitAccessControl: explicitAccessControl,
constructor: nil,
methods: [],
properties: [],
namespace: effectiveNamespace
)
let uniqueKey = classKey(name: name, namespace: effectiveNamespace)
stateStack.push(state: .classBody(name: name, key: uniqueKey))
exportedClassByName[uniqueKey] = exportedClass
exportedClassNames.append(uniqueKey)
return .visitChildren
}
override func visitPost(_ node: ClassDeclSyntax) {
// Make sure we pop the state stack only if we're in a class body state (meaning we successfully pushed)
if case .classBody(_, _) = stateStack.current {
stateStack.pop()
}
}
override func visit(_ node: EnumDeclSyntax) -> SyntaxVisitorContinueKind {
guard node.attributes.hasJSAttribute() else {
return .skipChildren
}
guard let jsAttribute = node.attributes.firstJSAttribute else {
return .skipChildren
}
let name = node.name.text
let rawType: String? = node.inheritanceClause?.inheritedTypes.first { inheritedType in
let typeName = inheritedType.type.trimmedDescription
return Constants.supportedRawTypes.contains(typeName)
}?.type.trimmedDescription
let attributeNamespace = extractNamespace(from: jsAttribute)
let computedNamespace = computeNamespace(for: node)
if computedNamespace != nil && attributeNamespace != nil {
diagnose(
node: jsAttribute,
message: "Nested enums cannot specify their own namespace",
hint: "Remove the namespace from @JS attribute - nested enums inherit namespace from parent"
)
return .skipChildren
}
currentEnum.name = name
currentEnum.cases = []
currentEnum.rawType = rawType
stateStack.push(state: .enumBody(name: name))
return .visitChildren
}
override func visitPost(_ node: EnumDeclSyntax) {
guard let jsAttribute = node.attributes.firstJSAttribute,
let enumName = currentEnum.name
else {
// Only pop if we have a valid enum that was processed
if case .enumBody(_) = stateStack.current {
stateStack.pop()
}
return
}
let attributeNamespace = extractNamespace(from: jsAttribute)
let computedNamespace = computeNamespace(for: node)
let effectiveNamespace: [String]?
if computedNamespace == nil && attributeNamespace != nil {
effectiveNamespace = attributeNamespace
} else {
effectiveNamespace = computedNamespace
}
let emitStyle = extractEnumStyle(from: jsAttribute) ?? .const
if case .tsEnum = emitStyle,
let raw = currentEnum.rawType,
let rawEnum = SwiftEnumRawType.from(raw), rawEnum == .bool
{
diagnose(
node: jsAttribute,
message: "TypeScript enum style is not supported for Bool raw-value enums",
hint: "Use enumStyle: .const or change the raw type to String or a numeric type"
)
}
if currentEnum.cases.contains(where: { !$0.associatedValues.isEmpty }) {
if case .tsEnum = emitStyle {
diagnose(
node: jsAttribute,
message: "TypeScript enum style is not supported for associated value enums",
hint: "Use enumStyle: .const in order to map associated-value enums"
)
}
for enumCase in currentEnum.cases {
for associatedValue in enumCase.associatedValues {
switch associatedValue.type {
case .string, .int, .float, .double, .bool:
break
case .optional(let wrappedType):
switch wrappedType {
case .string, .int, .float, .double, .bool:
break
default:
diagnose(
node: node,
message: "Unsupported associated value type: \(associatedValue.type.swiftType)",
hint:
"Only primitive types and optional primitives (String?, Int?, Float?, Double?, Bool?) are supported in associated-value enums"
)
}
default:
diagnose(
node: node,
message: "Unsupported associated value type: \(associatedValue.type.swiftType)",
hint:
"Only primitive types and optional primitives (String?, Int?, Float?, Double?, Bool?) are supported in associated-value enums"
)
}
}
}
}
let swiftCallName = ExportSwift.computeSwiftCallName(for: node, itemName: enumName)
let explicitAccessControl = computeExplicitAtLeastInternalAccessControl(
for: node,
message: "Enum visibility must be at least internal"
)
let exportedEnum = ExportedEnum(
name: enumName,
swiftCallName: swiftCallName,
explicitAccessControl: explicitAccessControl,
cases: currentEnum.cases,
rawType: currentEnum.rawType,
namespace: effectiveNamespace,
emitStyle: emitStyle
)
exportedEnumByName[enumName] = exportedEnum
exportedEnumNames.append(enumName)
currentEnum = CurrentEnum()
stateStack.pop()
}
override func visit(_ node: EnumCaseDeclSyntax) -> SyntaxVisitorContinueKind {
for element in node.elements {
let caseName = element.name.text
let rawValue: String?
var associatedValues: [AssociatedValue] = []
if currentEnum.rawType != nil {
if let stringLiteral = element.rawValue?.value.as(StringLiteralExprSyntax.self) {
rawValue = stringLiteral.segments.first?.as(StringSegmentSyntax.self)?.content.text
} else if let boolLiteral = element.rawValue?.value.as(BooleanLiteralExprSyntax.self) {
rawValue = boolLiteral.literal.text
} else if let intLiteral = element.rawValue?.value.as(IntegerLiteralExprSyntax.self) {
rawValue = intLiteral.literal.text
} else if let floatLiteral = element.rawValue?.value.as(FloatLiteralExprSyntax.self) {
rawValue = floatLiteral.literal.text
} else {
rawValue = nil
}
} else {
rawValue = nil
}
if let parameterClause = element.parameterClause {
for param in parameterClause.parameters {
guard let bridgeType = parent.lookupType(for: param.type) else {
diagnose(
node: param.type,
message: "Unsupported associated value type: \(param.type.trimmedDescription)",
hint: "Only primitive types and types defined in the same module are allowed"
)
continue
}
let label = param.firstName?.text
associatedValues.append(AssociatedValue(label: label, type: bridgeType))
}
}
let enumCase = EnumCase(
name: caseName,
rawValue: rawValue,
associatedValues: associatedValues
)
currentEnum.cases.append(enumCase)
}
return .visitChildren
}
/// Computes namespace by walking up the AST hierarchy to find parent namespace enums
/// If parent enum is a namespace enum (no cases) then it will be used as part of namespace for given node
///
///
/// Method allows for explicit namespace for top level enum, it will be used as base namespace and will concat enum name
private func computeNamespace(for node: some SyntaxProtocol) -> [String]? {
var namespace: [String] = []
var currentNode: Syntax? = node.parent
while let parent = currentNode {
if let enumDecl = parent.as(EnumDeclSyntax.self),
enumDecl.attributes.hasJSAttribute()
{
let isNamespaceEnum = !enumDecl.memberBlock.members.contains { member in
member.decl.is(EnumCaseDeclSyntax.self)
}
if isNamespaceEnum {
namespace.insert(enumDecl.name.text, at: 0)
if let jsAttribute = enumDecl.attributes.firstJSAttribute,
let explicitNamespace = extractNamespace(from: jsAttribute)
{
namespace = explicitNamespace + namespace
break
}
}
}
currentNode = parent.parent
}
return namespace.isEmpty ? nil : namespace
}
/// Requires the node to have at least internal access control.
private func computeExplicitAtLeastInternalAccessControl(
for node: some WithModifiersSyntax,
message: String
) -> String? {
guard let accessControl = node.explicitAccessControl else {
return nil
}
guard accessControl.isAtLeastInternal else {
diagnose(
node: accessControl,
message: message,
hint: "Use `internal`, `package` or `public` access control"
)
return nil
}
return accessControl.name.text
}
}
func parseSingleFile(_ sourceFile: SourceFileSyntax) throws -> [DiagnosticError] {
let collector = APICollector(parent: self)
collector.walk(sourceFile)
exportedFunctions.append(contentsOf: collector.exportedFunctions)
exportedClasses.append(
contentsOf: collector.exportedClassNames.map {
collector.exportedClassByName[$0]!
}
)
exportedEnums.append(
contentsOf: collector.exportedEnumNames.map {
collector.exportedEnumByName[$0]!
}
)
return collector.errors
}
/// Computes the full Swift call name by walking up the AST hierarchy to find all parent enums
/// This generates the qualified name needed for Swift code generation (e.g., "Networking.API.HTTPServer")
private static func computeSwiftCallName(for node: some SyntaxProtocol, itemName: String) -> String {
var swiftPath: [String] = []
var currentNode: Syntax? = node.parent
while let parent = currentNode {
if let enumDecl = parent.as(EnumDeclSyntax.self),
enumDecl.attributes.hasJSAttribute()
{
swiftPath.insert(enumDecl.name.text, at: 0)
}
currentNode = parent.parent
}
if swiftPath.isEmpty {
return itemName
} else {
return swiftPath.joined(separator: ".") + "." + itemName
}
}
func lookupType(for type: TypeSyntax) -> BridgeType? {
// T?
if let optionalType = type.as(OptionalTypeSyntax.self) {
let wrappedType = optionalType.wrappedType
if let baseType = lookupType(for: wrappedType) {
return .optional(baseType)
}
}
// Optional<T>
if let identifierType = type.as(IdentifierTypeSyntax.self),
identifierType.name.text == "Optional",
let genericArgs = identifierType.genericArgumentClause?.arguments,
genericArgs.count == 1,
let argType = genericArgs.first?.argument
{
if let baseType = lookupType(for: argType) {
return .optional(baseType)
}
}
// Swift.Optional<T>
if let memberType = type.as(MemberTypeSyntax.self),
let baseType = memberType.baseType.as(IdentifierTypeSyntax.self),
baseType.name.text == "Swift",
memberType.name.text == "Optional",
let genericArgs = memberType.genericArgumentClause?.arguments,
genericArgs.count == 1,
let argType = genericArgs.first?.argument
{
if let wrappedType = lookupType(for: argType) {
return .optional(wrappedType)
}
}
if let aliasDecl = typeDeclResolver.resolveTypeAlias(type) {
if let resolvedType = lookupType(for: aliasDecl.initializer.value) {
return resolvedType
}
}
let typeName = type.trimmedDescription
if let primitiveType = BridgeType(swiftType: typeName) {
return primitiveType
}
guard let typeDecl = typeDeclResolver.resolve(type) else {
return nil
}
if let enumDecl = typeDecl.as(EnumDeclSyntax.self) {
let swiftCallName = ExportSwift.computeSwiftCallName(for: enumDecl, itemName: enumDecl.name.text)
let rawTypeString = enumDecl.inheritanceClause?.inheritedTypes.first { inheritedType in
let typeName = inheritedType.type.trimmedDescription
return Constants.supportedRawTypes.contains(typeName)
}?.type.trimmedDescription
if let rawTypeString, let rawType = SwiftEnumRawType.from(rawTypeString) {
return .rawValueEnum(swiftCallName, rawType)
} else {
let hasAnyCases = enumDecl.memberBlock.members.contains { member in
member.decl.is(EnumCaseDeclSyntax.self)
}
if !hasAnyCases {
return .namespaceEnum(swiftCallName)
}
let hasAssociatedValues =
enumDecl.memberBlock.members.contains { member in
guard let caseDecl = member.decl.as(EnumCaseDeclSyntax.self) else { return false }
return caseDecl.elements.contains { element in
if let params = element.parameterClause?.parameters {
return !params.isEmpty
}
return false
}
}
if hasAssociatedValues {
return .associatedValueEnum(swiftCallName)
} else {
return .caseEnum(swiftCallName)
}
}
}
guard typeDecl.is(ClassDeclSyntax.self) || typeDecl.is(ActorDeclSyntax.self) else {
return nil
}
let swiftCallName = ExportSwift.computeSwiftCallName(for: typeDecl, itemName: typeDecl.name.text)
return .swiftHeapObject(swiftCallName)
}
static let prelude: DeclSyntax = """
// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit,
// DO NOT EDIT.
//
// To update this file, just rebuild your project or run
// `swift package bridge-js`.
@_spi(BridgeJS) import JavaScriptKit
"""
func renderSwiftGlue() throws -> String? {
var decls: [DeclSyntax] = []
guard exportedFunctions.count > 0 || exportedClasses.count > 0 || exportedEnums.count > 0 else {
return nil
}
decls.append(Self.prelude)
for enumDef in exportedEnums {
switch enumDef.enumType {
case .simple:
decls.append(enumCodegen.renderCaseEnumHelpers(enumDef))
case .rawValue:
decls.append("extension \(raw: enumDef.swiftCallName): _BridgedSwiftEnumNoPayload {}")
case .associatedValue:
decls.append(enumCodegen.renderAssociatedValueEnumHelpers(enumDef))
case .namespace:
()
}
}
for function in exportedFunctions {
decls.append(try renderSingleExportedFunction(function: function))
}
for klass in exportedClasses {
decls.append(contentsOf: try renderSingleExportedClass(klass: klass))
}
let format = BasicFormat()
return decls.map { $0.formatted(using: format).description }.joined(separator: "\n\n")
}
class ExportedThunkBuilder {
var body: [CodeBlockItemSyntax] = []
var liftedParameterExprs: [ExprSyntax] = []
var parameters: [Parameter] = []
var abiParameterSignatures: [(name: String, type: WasmCoreType)] = []
var abiReturnType: WasmCoreType?
let effects: Effects
init(effects: Effects) {
self.effects = effects
}
private func append(_ item: CodeBlockItemSyntax) {
var item = item
// Add a newline for items after the first one
if !self.body.isEmpty {
item = item.with(\.leadingTrivia, .newline)
}
self.body.append(item)
}
func liftParameter(param: Parameter) throws {
parameters.append(param)
let liftingInfo = try param.type.liftParameterInfo()
let argumentsToLift: [String]
if liftingInfo.parameters.count == 1 {
argumentsToLift = [param.name]
} else {
argumentsToLift = liftingInfo.parameters.map { (name, _) in param.name + name.capitalizedFirstLetter }
}
let typeNameForIntrinsic: String
switch param.type {
case .optional(let wrappedType):
typeNameForIntrinsic = "Optional<\(wrappedType.swiftType)>"
default:
typeNameForIntrinsic = param.type.swiftType
}
liftedParameterExprs.append(
ExprSyntax(
"\(raw: typeNameForIntrinsic).bridgeJSLiftParameter(\(raw: argumentsToLift.joined(separator: ", ")))"
)
)
for (name, type) in zip(argumentsToLift, liftingInfo.parameters.map { $0.type }) {
abiParameterSignatures.append((name, type))
}
}
private func removeFirstLiftedParameter() -> (parameter: Parameter, expr: ExprSyntax) {
let parameter = parameters.removeFirst()
let expr = liftedParameterExprs.removeFirst()
return (parameter, expr)
}
private func renderCallStatement(callee: ExprSyntax, returnType: BridgeType) -> CodeBlockItemSyntax {
let labeledParams = zip(parameters, liftedParameterExprs).map { param, expr in
LabeledExprSyntax(label: param.label, expression: expr)
}
var callExpr: ExprSyntax =
"\(raw: callee)(\(raw: labeledParams.map { $0.description }.joined(separator: ", ")))"
if effects.isAsync {
callExpr = ExprSyntax(
AwaitExprSyntax(awaitKeyword: .keyword(.await).with(\.trailingTrivia, .space), expression: callExpr)
)
}
if effects.isThrows {
callExpr = ExprSyntax(
TryExprSyntax(
tryKeyword: .keyword(.try).with(\.trailingTrivia, .space),
expression: callExpr
)
)
}
if effects.isAsync, returnType != .void {
return CodeBlockItemSyntax(item: .init(StmtSyntax("return \(raw: callExpr).jsValue")))
}
if returnType == .void {
return CodeBlockItemSyntax(item: .init(ExpressionStmtSyntax(expression: callExpr)))
} else {
return CodeBlockItemSyntax(item: .init(DeclSyntax("let ret = \(raw: callExpr)")))
}
}
func call(name: String, returnType: BridgeType) {
let item = renderCallStatement(callee: "\(raw: name)", returnType: returnType)
append(item)
}
func callMethod(klassName: String, methodName: String, returnType: BridgeType) {
let (_, selfExpr) = removeFirstLiftedParameter()
let item = renderCallStatement(
callee: "\(raw: selfExpr).\(raw: methodName)",
returnType: returnType
)
append(item)
}
func callPropertyGetter(klassName: String, propertyName: String, returnType: BridgeType) {
let (_, selfExpr) = removeFirstLiftedParameter()
if returnType == .void {
append("\(raw: selfExpr).\(raw: propertyName)")
} else {
append("let ret = \(raw: selfExpr).\(raw: propertyName)")
}
}
func callPropertySetter(klassName: String, propertyName: String) {
let (_, selfExpr) = removeFirstLiftedParameter()
let (_, newValueExpr) = removeFirstLiftedParameter()
append("\(raw: selfExpr).\(raw: propertyName) = \(raw: newValueExpr)")
}
func lowerReturnValue(returnType: BridgeType) throws {
if effects.isAsync {
// Async functions always return a Promise, which is a JSObject
try _lowerReturnValue(returnType: .jsObject(nil))
} else {
try _lowerReturnValue(returnType: returnType)
}
}