forked from swiftwasm/JavaScriptKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSwiftToSkeleton.swift
More file actions
2590 lines (2276 loc) · 98 KB
/
SwiftToSkeleton.swift
File metadata and controls
2590 lines (2276 loc) · 98 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 SwiftSyntax
import SwiftSyntaxBuilder
#if canImport(BridgeJSUtilities)
import BridgeJSUtilities
#endif
#if canImport(BridgeJSSkeleton)
import BridgeJSSkeleton
#endif
/// Builds BridgeJS skeletons from Swift source files using SwiftSyntax walk for API collection.
///
/// This is a shared entry point for producing:
/// - exported skeletons from `@JS` declarations
/// - imported skeletons from `@JSFunction/@JSGetter/@JSSetter/@JSClass` macro signatures
public final class SwiftToSkeleton {
public let progress: ProgressReporting
public let moduleName: String
public let exposeToGlobal: Bool
private var sourceFiles: [(sourceFile: SourceFileSyntax, inputFilePath: String)] = []
let typeDeclResolver: TypeDeclResolver
public init(progress: ProgressReporting, moduleName: String, exposeToGlobal: Bool) {
self.progress = progress
self.moduleName = moduleName
self.exposeToGlobal = exposeToGlobal
self.typeDeclResolver = TypeDeclResolver()
// Index known types provided by JavaScriptKit
self.typeDeclResolver.addSourceFile(
"""
@JSClass struct JSPromise {}
"""
)
}
public func addSourceFile(_ sourceFile: SourceFileSyntax, inputFilePath: String) {
self.typeDeclResolver.addSourceFile(sourceFile)
sourceFiles.append((sourceFile, inputFilePath))
}
public func finalize() throws -> BridgeJSSkeleton {
var perSourceErrors: [(inputFilePath: String, errors: [DiagnosticError])] = []
var importedFiles: [ImportedFileSkeleton] = []
var exported = ExportedSkeleton(functions: [], classes: [], enums: [], exposeToGlobal: exposeToGlobal)
for (sourceFile, inputFilePath) in sourceFiles {
progress.print("Processing \(inputFilePath)")
let exportCollector = ExportSwiftAPICollector(parent: self)
exportCollector.walk(sourceFile)
let typeNameCollector = ImportSwiftMacrosJSImportTypeNameCollector(viewMode: .sourceAccurate)
typeNameCollector.walk(sourceFile)
let importCollector = ImportSwiftMacrosAPICollector(
inputFilePath: inputFilePath,
knownJSClassNames: typeNameCollector.typeNames,
parent: self
)
importCollector.walk(sourceFile)
let importErrorsFatal = importCollector.errors.filter { !$0.message.contains("Unsupported type '") }
if !exportCollector.errors.isEmpty || !importErrorsFatal.isEmpty {
perSourceErrors.append(
(inputFilePath: inputFilePath, errors: exportCollector.errors + importErrorsFatal)
)
}
importedFiles.append(
ImportedFileSkeleton(
functions: importCollector.importedFunctions,
types: importCollector.importedTypes,
globalGetters: importCollector.importedGlobalGetters
)
)
exportCollector.finalize(&exported)
}
if !perSourceErrors.isEmpty {
let allErrors = perSourceErrors.flatMap { inputFilePath, errors in
errors.map { $0.formattedDescription(fileName: inputFilePath) }
}
throw BridgeJSCoreError(allErrors.joined(separator: "\n"))
}
let importedSkeleton: ImportedModuleSkeleton? = {
let module = ImportedModuleSkeleton(children: importedFiles)
if module.children.allSatisfy({ $0.functions.isEmpty && $0.types.isEmpty && $0.globalGetters.isEmpty }) {
return nil
}
return module
}()
return BridgeJSSkeleton(moduleName: moduleName, exported: exported, imported: importedSkeleton)
}
func lookupType(for type: TypeSyntax, errors: inout [DiagnosticError]) -> BridgeType? {
if let attributedType = type.as(AttributedTypeSyntax.self) {
return lookupType(for: attributedType.baseType, errors: &errors)
}
// (T1, T2, ...) -> R
if let functionType = type.as(FunctionTypeSyntax.self) {
var parameters: [BridgeType] = []
for param in functionType.parameters {
guard let paramType = lookupType(for: param.type, errors: &errors) else {
return nil
}
parameters.append(paramType)
}
guard let returnType = lookupType(for: functionType.returnClause.type, errors: &errors) else {
return nil
}
let isAsync = functionType.effectSpecifiers?.asyncSpecifier != nil
let isThrows = functionType.effectSpecifiers?.throwsClause != nil
return .closure(
ClosureSignature(
parameters: parameters,
returnType: returnType,
moduleName: moduleName,
isAsync: isAsync,
isThrows: isThrows
)
)
}
// T?
if let optionalType = type.as(OptionalTypeSyntax.self) {
let wrappedType = optionalType.wrappedType
if let baseType = lookupType(for: wrappedType, errors: &errors) {
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 = TypeSyntax(genericArgs.first?.argument)
{
if let baseType = lookupType(for: argType, errors: &errors) {
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 = TypeSyntax(genericArgs.first?.argument)
{
if let wrappedType = lookupType(for: argType, errors: &errors) {
return .optional(wrappedType)
}
}
// [T]
if let arrayType = type.as(ArrayTypeSyntax.self) {
if let elementType = lookupType(for: arrayType.element, errors: &errors) {
return .array(elementType)
}
}
// Array<T>
if let identifierType = type.as(IdentifierTypeSyntax.self),
identifierType.name.text == "Array",
let genericArgs = identifierType.genericArgumentClause?.arguments,
genericArgs.count == 1,
let argType = TypeSyntax(genericArgs.first?.argument)
{
if let elementType = lookupType(for: argType, errors: &errors) {
return .array(elementType)
}
}
// Swift.Array<T>
if let memberType = type.as(MemberTypeSyntax.self),
let baseType = memberType.baseType.as(IdentifierTypeSyntax.self),
baseType.name.text == "Swift",
memberType.name.text == "Array",
let genericArgs = memberType.genericArgumentClause?.arguments,
genericArgs.count == 1,
let argType = TypeSyntax(genericArgs.first?.argument)
{
if let elementType = lookupType(for: argType, errors: &errors) {
return .array(elementType)
}
}
if let aliasDecl = typeDeclResolver.resolveTypeAlias(type) {
if let resolvedType = lookupType(for: aliasDecl.initializer.value, errors: &errors) {
return resolvedType
}
}
// UnsafePointer family
if let unsafePointerType = Self.parseUnsafePointerType(type) {
return .unsafePointer(unsafePointerType)
}
let typeName: String
if let identifier = type.as(IdentifierTypeSyntax.self) {
typeName = Self.normalizeIdentifier(identifier.name.text)
} else {
typeName = type.trimmedDescription
}
if let primitiveType = BridgeType(swiftType: typeName) {
return primitiveType
}
guard let typeDecl = typeDeclResolver.resolve(type) else {
errors.append(
DiagnosticError(
node: type,
message: "Unsupported type '\(type.trimmedDescription)'.",
hint: "Only primitive types and types defined in the same module are allowed"
)
)
return nil
}
if typeDecl.is(ProtocolDeclSyntax.self) {
let swiftCallName = SwiftToSkeleton.computeSwiftCallName(for: typeDecl, itemName: typeDecl.name.text)
return .swiftProtocol(swiftCallName)
}
if let enumDecl = typeDecl.as(EnumDeclSyntax.self) {
let swiftCallName = SwiftToSkeleton.computeSwiftCallName(for: enumDecl, itemName: enumDecl.name.text)
let rawTypeString = enumDecl.inheritanceClause?.inheritedTypes.first { inheritedType in
let typeName = inheritedType.type.trimmedDescription
return ExportSwiftConstants.supportedRawTypes.contains(typeName)
}?.type.trimmedDescription
if let rawType = SwiftEnumRawType(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)
}
}
}
if let structDecl = typeDecl.as(StructDeclSyntax.self) {
let swiftCallName = SwiftToSkeleton.computeSwiftCallName(for: structDecl, itemName: structDecl.name.text)
if structDecl.attributes.hasAttribute(name: "JSClass") {
return .jsObject(swiftCallName)
}
return .swiftStruct(swiftCallName)
}
guard typeDecl.is(ClassDeclSyntax.self) || typeDecl.is(ActorDeclSyntax.self) else {
return nil
}
let swiftCallName = SwiftToSkeleton.computeSwiftCallName(for: typeDecl, itemName: typeDecl.name.text)
// A type annotated with @JSClass is a JavaScript object wrapper (imported),
// even if it is declared as a Swift class.
if let classDecl = typeDecl.as(ClassDeclSyntax.self), classDecl.attributes.hasAttribute(name: "JSClass") {
return .jsObject(swiftCallName)
}
if let actorDecl = typeDecl.as(ActorDeclSyntax.self), actorDecl.attributes.hasAttribute(name: "JSClass") {
return .jsObject(swiftCallName)
}
return .swiftHeapObject(swiftCallName)
}
fileprivate static func parseUnsafePointerType(_ type: TypeSyntax) -> UnsafePointerType? {
func parse(baseName: String, genericArg: TypeSyntax?) -> UnsafePointerType? {
let pointee = genericArg?.trimmedDescription
switch baseName {
case "UnsafePointer":
return .init(kind: .unsafePointer, pointee: pointee)
case "UnsafeMutablePointer":
return .init(kind: .unsafeMutablePointer, pointee: pointee)
case "UnsafeRawPointer":
return .init(kind: .unsafeRawPointer)
case "UnsafeMutableRawPointer":
return .init(kind: .unsafeMutableRawPointer)
case "OpaquePointer":
return .init(kind: .opaquePointer)
default:
return nil
}
}
if let identifier = type.as(IdentifierTypeSyntax.self) {
let baseName = identifier.name.text
if (baseName == "UnsafePointer" || baseName == "UnsafeMutablePointer"),
let genericArgs = identifier.genericArgumentClause?.arguments,
genericArgs.count == 1,
let argType = TypeSyntax(genericArgs.first?.argument)
{
return parse(baseName: baseName, genericArg: argType)
}
return parse(baseName: baseName, genericArg: nil)
}
if let member = type.as(MemberTypeSyntax.self),
let base = member.baseType.as(IdentifierTypeSyntax.self),
base.name.text == "Swift"
{
let baseName = member.name.text
if (baseName == "UnsafePointer" || baseName == "UnsafeMutablePointer"),
let genericArgs = member.genericArgumentClause?.arguments,
genericArgs.count == 1,
let argType = TypeSyntax(genericArgs.first?.argument)
{
return parse(baseName: baseName, genericArg: argType)
}
return parse(baseName: baseName, genericArg: nil)
}
return nil
}
/// 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")
fileprivate 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
}
}
/// Strips surrounding backticks from an identifier (e.g. "`Foo`" -> "Foo").
static func normalizeIdentifier(_ name: String) -> String {
guard name.hasPrefix("`"), name.hasSuffix("`"), name.count >= 2 else {
return name
}
return String(name.dropFirst().dropLast())
}
}
private enum ExportSwiftConstants {
static let supportedRawTypes = SwiftEnumRawType.allCases.map { $0.rawValue }
}
extension AttributeListSyntax {
func hasJSAttribute() -> Bool {
firstJSAttribute != nil
}
var firstJSAttribute: AttributeSyntax? {
first(where: {
$0.as(AttributeSyntax.self)?.attributeName.trimmedDescription == "JS"
})?.as(AttributeSyntax.self)
}
/// Returns true if any attribute has the given name (e.g. "JSClass").
func hasAttribute(name: String) -> Bool {
contains { attribute in
guard let syntax = attribute.as(AttributeSyntax.self) else { return false }
return syntax.attributeName.trimmedDescription == name
}
}
}
private final class ExportSwiftAPICollector: 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] = []
func finalize(_ result: inout ExportedSkeleton) {
result.functions.append(contentsOf: exportedFunctions)
result.classes.append(contentsOf: exportedClassNames.map { exportedClassByName[$0]! })
result.enums.append(contentsOf: exportedEnumNames.map { exportedEnumByName[$0]! })
result.structs.append(contentsOf: exportedStructNames.map { exportedStructByName[$0]! })
result.protocols.append(contentsOf: exportedProtocolNames.map { exportedProtocolByName[$0]! })
}
/// 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: SwiftToSkeleton
init(parent: SwiftToSkeleton) {
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 withLookupErrors<T>(_ body: (inout [DiagnosticError]) -> T) -> T {
var errs = self.errors
defer { self.errors = errs }
return body(&errs)
}
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)
// Array literals are allowed but checked in extractArrayDefaultValue
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 arrayExpr = expr.as(ArrayExprSyntax.self) {
return extractArrayDefaultValue(from: arrayExpr, 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
}
/// Extracts default value from an array literal expression
private func extractArrayDefaultValue(
from arrayExpr: ArrayExprSyntax,
type: BridgeType
) -> DefaultValue? {
// Verify the type is an array type
let elementType: BridgeType?
switch type {
case .array(let element):
elementType = element
case .optional(.array(let element)):
elementType = element
default:
diagnose(
node: arrayExpr,
message: "Array literal is only valid for array parameters",
hint: "Parameter type should be an array like [Int] or [String]"
)
return nil
}
var elements: [DefaultValue] = []
for element in arrayExpr.elements {
guard let elementValue = extractLiteralValue(from: element.expression, type: elementType) else {
diagnose(
node: element.expression,
message: "Array element must be a literal value",
hint: "Use simple literals like \"text\", 42, true, false in array elements"
)
return nil
}
elements.append(elementValue)
}
return .array(elements)
}
/// 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 = withLookupErrors { self.parent.lookupType(for: param.type, errors: &$0) }
guard let type = resolvedType else {
continue // Skip unsupported types
}
if 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 case .optional(let wrappedType) = type, wrappedType.isOptional {
diagnoseNestedOptional(node: param.type, type: param.type.trimmedDescription)
continue
}
if case .optional(let wrappedType) = type, wrappedType.isOptional {
diagnoseNestedOptional(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 = withLookupErrors { self.parent.lookupType(for: returnClause.type, errors: &$0) }
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 { 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
let swiftCallName = exportedEnumByName[enumKey]?.swiftCallName ?? enumName
staticContext = isNamespaceEnum ? .namespaceEnum(swiftCallName) : .enumName(enumName)
case .protocolBody(_, _):
return nil
case .structBody(let structName, _):
if isStatic {
staticContext = .structName(structName)
} else {