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
3509 lines (3118 loc) · 146 KB
/
ExportSwift.swift
File metadata and controls
3509 lines (3118 loc) · 146 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 let exposeToGlobal: Bool
private var exportedFunctions: [ExportedFunction] = []
private var exportedClasses: [ExportedClass] = []
private var exportedEnums: [ExportedEnum] = []
private var exportedStructs: [ExportedStruct] = []
private var exportedProtocols: [ExportedProtocol] = []
private var exportedProtocolNameByKey: [String: String] = [:]
private var typeDeclResolver: TypeDeclResolver = TypeDeclResolver()
private let enumCodegen: EnumCodegen = EnumCodegen()
private let closureCodegen = ClosureCodegen()
public init(progress: ProgressReporting, moduleName: String, exposeToGlobal: Bool) {
self.progress = progress
self.moduleName = moduleName
self.exposeToGlobal = exposeToGlobal
}
/// 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
///
/// - Parameters:
/// - exposeToGlobal: Whether to expose exported APIs to the global namespace (default: false)
/// - 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,
structs: exportedStructs,
protocols: exportedProtocols,
exposeToGlobal: exposeToGlobal
)
)
}
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] = [:]
/// The names of the exported protocols, in the order they were written in the source file
var exportedProtocolNames: [String] = []
var exportedProtocolByName: [String: ExportedProtocol] = [:]
/// The names of the exported structs, in the order they were written in the source file
var exportedStructNames: [String] = []
var exportedStructByName: [String: ExportedStruct] = [:]
var errors: [DiagnosticError] = []
/// Creates a unique key by combining name and namespace
private func makeKey(name: String, namespace: [String]?) -> String {
if let namespace = namespace, !namespace.isEmpty {
return "\(namespace.joined(separator: ".")).\(name)"
} else {
return name
}
}
struct NamespaceResolution {
let namespace: [String]?
let isValid: Bool
}
/// Resolves and validates namespace from both @JS attribute and computed (nested) namespace
/// Returns the effective namespace and whether validation succeeded
private func resolveNamespace(
from jsAttribute: AttributeSyntax,
for node: some SyntaxProtocol,
declarationType: String
) -> NamespaceResolution {
let attributeNamespace = extractNamespace(from: jsAttribute)
let computedNamespace = computeNamespace(for: node)
if computedNamespace != nil && attributeNamespace != nil {
diagnose(
node: jsAttribute,
message: "Nested \(declarationType)s cannot specify their own namespace",
hint:
"Remove the namespace from @JS attribute - nested \(declarationType)s inherit namespace from parent"
)
return NamespaceResolution(namespace: nil, isValid: false)
}
return NamespaceResolution(namespace: computedNamespace ?? attributeNamespace, isValid: true)
}
enum State {
case topLevel
case classBody(name: String, key: String)
case enumBody(name: String, key: String)
case protocolBody(name: String, key: String)
case structBody(name: String, key: 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>>"
)
}
/// Detects whether given expression is supported as default parameter value
private func isSupportedDefaultValueExpression(_ initClause: InitializerClauseSyntax) -> Bool {
let expression = initClause.value
// Function calls are checked later in extractDefaultValue (as constructors are allowed)
if expression.is(ArrayExprSyntax.self) { return false }
if expression.is(DictionaryExprSyntax.self) { return false }
if expression.is(BinaryOperatorExprSyntax.self) { return false }
if expression.is(ClosureExprSyntax.self) { return false }
// Method call chains (e.g., obj.foo())
if let memberExpression = expression.as(MemberAccessExprSyntax.self),
memberExpression.base?.is(FunctionCallExprSyntax.self) == true
{
return false
}
return true
}
/// Extract enum case value from member access expression
private func extractEnumCaseValue(
from memberExpr: MemberAccessExprSyntax,
type: BridgeType
) -> DefaultValue? {
let caseName = memberExpr.declName.baseName.text
let enumName: String?
switch type {
case .caseEnum(let name), .rawValueEnum(let name, _), .associatedValueEnum(let name):
enumName = name
case .optional(let wrappedType):
switch wrappedType {
case .caseEnum(let name), .rawValueEnum(let name, _), .associatedValueEnum(let name):
enumName = name
default:
return nil
}
default:
return nil
}
guard let enumName = enumName else { return nil }
if memberExpr.base == nil {
return .enumCase(enumName, caseName)
}
if let baseExpr = memberExpr.base?.as(DeclReferenceExprSyntax.self) {
let baseName = baseExpr.baseName.text
let lastComponent = enumName.split(separator: ".").last.map(String.init) ?? enumName
if baseName == enumName || baseName == lastComponent {
return .enumCase(enumName, caseName)
}
}
return nil
}
/// Extracts default value from parameter's default value clause
private func extractDefaultValue(
from defaultClause: InitializerClauseSyntax?,
type: BridgeType
) -> DefaultValue? {
guard let defaultClause = defaultClause else {
return nil
}
if !isSupportedDefaultValueExpression(defaultClause) {
diagnose(
node: defaultClause,
message: "Complex default parameter expressions are not supported",
hint: "Use simple literal values (e.g., \"text\", 42, true, nil) or simple constants"
)
return nil
}
let expr = defaultClause.value
if expr.is(NilLiteralExprSyntax.self) {
guard case .optional(_) = type else {
diagnose(
node: expr,
message: "nil is only valid for optional parameters",
hint: "Make the parameter optional by adding ? to the type"
)
return nil
}
return .null
}
if let memberExpr = expr.as(MemberAccessExprSyntax.self),
let enumValue = extractEnumCaseValue(from: memberExpr, type: type)
{
return enumValue
}
if let funcCall = expr.as(FunctionCallExprSyntax.self) {
return extractConstructorDefaultValue(from: funcCall, type: type)
}
if let literalValue = extractLiteralValue(from: expr, type: type) {
return literalValue
}
diagnose(
node: expr,
message: "Unsupported default parameter value expression",
hint: "Use simple literal values like \"text\", 42, true, false, nil, or enum cases like .caseName"
)
return nil
}
/// Extracts default value from a constructor call expression
private func extractConstructorDefaultValue(
from funcCall: FunctionCallExprSyntax,
type: BridgeType
) -> DefaultValue? {
guard let calledExpr = funcCall.calledExpression.as(DeclReferenceExprSyntax.self) else {
diagnose(
node: funcCall,
message: "Complex constructor expressions are not supported",
hint: "Use a simple constructor call like ClassName() or ClassName(arg: value)"
)
return nil
}
let typeName = calledExpr.baseName.text
let isStructType: Bool
let expectedTypeName: String?
switch type {
case .swiftStruct(let name), .optional(.swiftStruct(let name)):
isStructType = true
expectedTypeName = name.split(separator: ".").last.map(String.init)
case .swiftHeapObject(let name), .optional(.swiftHeapObject(let name)):
isStructType = false
expectedTypeName = name.split(separator: ".").last.map(String.init)
default:
diagnose(
node: funcCall,
message: "Constructor calls are only supported for class and struct types",
hint: "Parameter type should be a Swift class or struct"
)
return nil
}
guard let expectedTypeName = expectedTypeName, typeName == expectedTypeName else {
diagnose(
node: funcCall,
message: "Constructor type name '\(typeName)' doesn't match parameter type",
hint: "Ensure the constructor matches the parameter type"
)
return nil
}
if isStructType {
// For structs, extract field name/value pairs
var fields: [DefaultValueField] = []
for argument in funcCall.arguments {
guard let fieldName = argument.label?.text else {
diagnose(
node: argument,
message: "Struct initializer arguments must have labels",
hint: "Use labeled arguments like MyStruct(x: 1, y: 2)"
)
return nil
}
guard let fieldValue = extractLiteralValue(from: argument.expression) else {
diagnose(
node: argument.expression,
message: "Struct field value must be a literal",
hint: "Use simple literals like \"text\", 42, true, false in struct fields"
)
return nil
}
fields.append(DefaultValueField(name: fieldName, value: fieldValue))
}
return .structLiteral(typeName, fields)
} else {
if funcCall.arguments.isEmpty {
return .object(typeName)
}
var constructorArgs: [DefaultValue] = []
for argument in funcCall.arguments {
guard let argValue = extractLiteralValue(from: argument.expression) else {
diagnose(
node: argument.expression,
message: "Constructor argument must be a literal value",
hint: "Use simple literals like \"text\", 42, true, false in constructor arguments"
)
return nil
}
constructorArgs.append(argValue)
}
return .objectWithArguments(typeName, constructorArgs)
}
}
/// Extracts a literal value from an expression with optional type checking
private func extractLiteralValue(from expr: ExprSyntax, type: BridgeType? = nil) -> DefaultValue? {
if expr.is(NilLiteralExprSyntax.self) {
return .null
}
if let stringLiteral = expr.as(StringLiteralExprSyntax.self),
let segment = stringLiteral.segments.first?.as(StringSegmentSyntax.self)
{
let value = DefaultValue.string(segment.content.text)
if let type = type, !type.isCompatibleWith(.string) {
return nil
}
return value
}
if let boolLiteral = expr.as(BooleanLiteralExprSyntax.self) {
let value = DefaultValue.bool(boolLiteral.literal.text == "true")
if let type = type, !type.isCompatibleWith(.bool) {
return nil
}
return value
}
var numericExpr = expr
var isNegative = false
if let prefixExpr = expr.as(PrefixOperatorExprSyntax.self),
prefixExpr.operator.text == "-"
{
numericExpr = prefixExpr.expression
isNegative = true
}
if let intLiteral = numericExpr.as(IntegerLiteralExprSyntax.self),
let intValue = Int(intLiteral.literal.text)
{
let value = DefaultValue.int(isNegative ? -intValue : intValue)
if let type = type, !type.isCompatibleWith(.int) {
return nil
}
return value
}
if let floatLiteral = numericExpr.as(FloatLiteralExprSyntax.self) {
if let floatValue = Float(floatLiteral.literal.text) {
let value = DefaultValue.float(isNegative ? -floatValue : floatValue)
if type == nil || type?.isCompatibleWith(.float) == true {
return value
}
}
if let doubleValue = Double(floatLiteral.literal.text) {
let value = DefaultValue.double(isNegative ? -doubleValue : doubleValue)
if type == nil || type?.isCompatibleWith(.double) == true {
return value
}
}
}
return nil
}
/// Shared parameter parsing logic used by functions, initializers, and protocol methods
private func parseParameters(
from parameterClause: FunctionParameterClauseSyntax,
allowDefaults: Bool = true
) -> [Parameter] {
var parameters: [Parameter] = []
for param in parameterClause.parameters {
let resolvedType = self.parent.lookupType(for: param.type)
if let type = resolvedType, case .closure(let signature) = type {
if signature.isAsync {
diagnose(
node: param.type,
message: "Async is not supported for Swift closures yet."
)
continue
}
if signature.isThrows {
diagnose(
node: param.type,
message: "Throws is not supported for Swift closures yet."
)
continue
}
}
if let type = resolvedType, case .optional(let wrappedType) = type, wrappedType.isOptional {
diagnoseNestedOptional(node: param.type, type: param.type.trimmedDescription)
continue
}
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
let defaultValue: DefaultValue?
if allowDefaults {
defaultValue = extractDefaultValue(from: param.defaultValue, type: type)
} else {
defaultValue = nil
}
parameters.append(Parameter(label: label, name: name, type: type, defaultValue: defaultValue))
}
return parameters
}
override func visit(_ node: FunctionDeclSyntax) -> SyntaxVisitorContinueKind {
guard node.attributes.hasJSAttribute() else {
return .skipChildren
}
let isStatic = node.modifiers.contains { modifier in
modifier.name.tokenKind == .keyword(.static) || modifier.name.tokenKind == .keyword(.class)
}
switch state {
case .topLevel:
if isStatic {
diagnose(node: node, message: "Top-level functions cannot be static")
return .skipChildren
}
if let exportedFunction = visitFunction(node: node, isStatic: false) {
exportedFunctions.append(exportedFunction)
}
return .skipChildren
case .classBody(let className, let classKey):
if let exportedFunction = visitFunction(
node: node,
isStatic: isStatic,
className: className,
classKey: classKey
) {
exportedClassByName[classKey]?.methods.append(exportedFunction)
}
return .skipChildren
case .enumBody(let enumName, let enumKey):
if !isStatic {
diagnose(node: node, message: "Only static functions are supported in enums")
return .skipChildren
}
if let exportedFunction = visitFunction(node: node, isStatic: isStatic, enumName: enumName) {
if var currentEnum = exportedEnumByName[enumKey] {
currentEnum.staticMethods.append(exportedFunction)
exportedEnumByName[enumKey] = currentEnum
}
}
return .skipChildren
case .protocolBody(_, _):
// Protocol methods are handled in visitProtocolMethod during protocol parsing
return .skipChildren
case .structBody(let structName, let structKey):
if let exportedFunction = visitFunction(node: node, isStatic: isStatic, structName: structName) {
if var currentStruct = exportedStructByName[structKey] {
currentStruct.methods.append(exportedFunction)
exportedStructByName[structKey] = currentStruct
}
}
return .skipChildren
}
}
private func visitFunction(
node: FunctionDeclSyntax,
isStatic: Bool,
className: String? = nil,
classKey: String? = nil,
enumName: String? = nil,
structName: String? = nil
) -> ExportedFunction? {
guard let jsAttribute = node.attributes.firstJSAttribute else {
return nil
}
let name = node.name.text
let attributeNamespace = extractNamespace(from: jsAttribute)
let computedNamespace = computeNamespace(for: node)
let finalNamespace: [String]?
if let computed = computedNamespace, !computed.isEmpty {
finalNamespace = computed
} else {
finalNamespace = attributeNamespace
}
if attributeNamespace != 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"
)
}
if attributeNamespace != nil, case .enumBody = state {
diagnose(
node: jsAttribute,
message: "Namespace is not supported for enum static functions",
hint: "Remove the namespace from @JS attribute - enum functions inherit namespace from enum"
)
}
let parameters = parseParameters(from: node.signature.parameterClause, allowDefaults: true)
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
let staticContext: StaticContext?
switch state {
case .topLevel:
staticContext = nil
case .classBody(let className, _):
if isStatic {
staticContext = .className(className)
} else {
staticContext = nil
}
case .enumBody(let enumName, let enumKey):
if !isStatic {
diagnose(node: node, message: "Only static functions are supported in enums")
return nil
}
let isNamespaceEnum = exportedEnumByName[enumKey]?.cases.isEmpty ?? true
staticContext = isNamespaceEnum ? .namespaceEnum : .enumName(enumName)
case .protocolBody(_, _):
return nil
case .structBody(let structName, _):
if isStatic {
staticContext = .structName(structName)
} else {
staticContext = nil
}
}
let classNameForABI: String?
switch state {
case .classBody(let className, _):
classNameForABI = className
case .structBody(let structName, _):
classNameForABI = structName
default:
classNameForABI = nil
}
abiName = ABINameGenerator.generateABIName(
baseName: name,
namespace: finalNamespace,
staticContext: isStatic ? staticContext : nil,
className: classNameForABI
)
guard let effects = collectEffects(signature: node.signature, isStatic: isStatic) else {
return nil
}
return ExportedFunction(
name: name,
abiName: abiName,
parameters: parameters,
returnType: returnType,
effects: effects,
namespace: finalNamespace,
staticContext: staticContext
)
}
private func collectEffects(signature: FunctionSignatureSyntax, isStatic: Bool = false) -> 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, isStatic: isStatic)
}
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 let jsAttribute = node.attributes.firstJSAttribute else { return .skipChildren }
switch state {
case .classBody(let className, let classKey):
if extractNamespace(from: jsAttribute) != nil {
diagnose(
node: jsAttribute,
message: "Namespace is not supported for initializer declarations",
hint: "Remove the namespace from @JS attribute"
)
}
let parameters = parseParameters(from: node.signature.parameterClause, allowDefaults: true)
guard let effects = collectEffects(signature: node.signature) else {
return .skipChildren
}
let constructor = ExportedConstructor(
abiName: "bjs_\(className)_init",
parameters: parameters,
effects: effects
)
exportedClassByName[classKey]?.constructor = constructor
case .structBody(let structName, let structKey):
if extractNamespace(from: jsAttribute) != nil {
diagnose(
node: jsAttribute,
message: "Namespace is not supported for initializer declarations",
hint: "Remove the namespace from @JS attribute"
)
}
let parameters = parseParameters(from: node.signature.parameterClause, allowDefaults: true)
guard let effects = collectEffects(signature: node.signature) else {
return .skipChildren
}
let constructor = ExportedConstructor(
abiName: "bjs_\(structName)_init",
parameters: parameters,
effects: effects
)
exportedStructByName[structKey]?.constructor = constructor
case .enumBody(_, _):
diagnose(node: node, message: "Initializers are not supported inside enums")
case .topLevel, .protocolBody(_, _):
diagnose(node: node, message: "@JS init must be inside a @JS class or struct")
}
return .skipChildren
}
override func visit(_ node: VariableDeclSyntax) -> SyntaxVisitorContinueKind {
guard let jsAttribute = node.attributes.firstJSAttribute else { return .skipChildren }
let isStatic = node.modifiers.contains { modifier in
modifier.name.tokenKind == .keyword(.static) || modifier.name.tokenKind == .keyword(.class)
}
let attributeNamespace = extractNamespace(from: jsAttribute)
if attributeNamespace != nil {
diagnose(
node: jsAttribute,
message: "Namespace parameter within @JS attribute is not supported for property declarations",
hint:
"Remove the namespace from @JS attribute. If you need dedicated namespace, consider using a nested enum or class instead."
)
}
let computedNamespace = computeNamespace(for: node)
let finalNamespace: [String]?
if let computed = computedNamespace, !computed.isEmpty {
finalNamespace = computed
} else {
finalNamespace = nil
}
// Determine static context and validate placement
let staticContext: StaticContext?
switch state {
case .classBody(let className, _):
staticContext = isStatic ? .className(className) : nil
case .enumBody(let enumName, let enumKey):
if !isStatic {
diagnose(node: node, message: "Only static properties are supported in enums")
return .skipChildren
}
let isNamespaceEnum = exportedEnumByName[enumKey]?.cases.isEmpty ?? true
staticContext = isStatic ? (isNamespaceEnum ? .namespaceEnum : .enumName(enumName)) : nil
case .topLevel:
diagnose(node: node, message: "@JS var must be inside a @JS class or enum")
return .skipChildren
case .protocolBody(let protocolName, let protocolKey):
return visitProtocolProperty(node: node, protocolName: protocolName, protocolKey: protocolKey)
case .structBody(let structName, _):
if isStatic {
staticContext = .structName(structName)
} else {
diagnose(node: node, message: "@JS var must be static in structs (instance fields don't need @JS)")
return .skipChildren
}
}
// 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: { self.hasOnlyGetter($0.accessorBlock) })
let isReadonly = isLet || isGetterOnly
let exportedProperty = ExportedProperty(
name: propertyName,
type: propertyType,
isReadonly: isReadonly,
isStatic: isStatic,
namespace: finalNamespace,
staticContext: staticContext
)
if case .enumBody(_, let key) = state {
if var currentEnum = exportedEnumByName[key] {
currentEnum.staticProperties.append(exportedProperty)
exportedEnumByName[key] = currentEnum
}
} else if case .structBody(_, let key) = state {
exportedStructByName[key]?.properties.append(exportedProperty)
} else if case .classBody(_, let key) = state {
exportedClassByName[key]?.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 namespaceResult = resolveNamespace(from: jsAttribute, for: node, declarationType: "class")
guard namespaceResult.isValid else {
return .skipChildren
}
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: namespaceResult.namespace
)
let uniqueKey = makeKey(name: name, namespace: namespaceResult.namespace)
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 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 namespaceResult = resolveNamespace(from: jsAttribute, for: node, declarationType: "enum")
guard namespaceResult.isValid else {
return .skipChildren
}
let emitStyle = extractEnumStyle(from: jsAttribute) ?? .const
let swiftCallName = ExportSwift.computeSwiftCallName(for: node, itemName: name)
let explicitAccessControl = computeExplicitAtLeastInternalAccessControl(
for: node,
message: "Enum visibility must be at least internal"
)
let tsFullPath: String
if let namespace = namespaceResult.namespace, !namespace.isEmpty {
tsFullPath = namespace.joined(separator: ".") + "." + name
} else {
tsFullPath = name
}
// Create enum directly in dictionary
let exportedEnum = ExportedEnum(
name: name,
swiftCallName: swiftCallName,
tsFullPath: tsFullPath,
explicitAccessControl: explicitAccessControl,
cases: [], // Will be populated in visit(EnumCaseDeclSyntax)
rawType: SwiftEnumRawType(rawType),
namespace: namespaceResult.namespace,
emitStyle: emitStyle,
staticMethods: [],
staticProperties: []
)
let enumUniqueKey = makeKey(name: name, namespace: namespaceResult.namespace)
exportedEnumByName[enumUniqueKey] = exportedEnum
exportedEnumNames.append(enumUniqueKey)
stateStack.push(state: .enumBody(name: name, key: enumUniqueKey))
return .visitChildren
}
override func visitPost(_ node: EnumDeclSyntax) {
guard let jsAttribute = node.attributes.firstJSAttribute else {
// Only pop if we have a valid enum that was processed
if case .enumBody(_, _) = stateStack.current {
stateStack.pop()