-
-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathKotlinBridgeToKotlinVisitor.swift
More file actions
2047 lines (1922 loc) · 123 KB
/
Copy pathKotlinBridgeToKotlinVisitor.swift
File metadata and controls
2047 lines (1922 loc) · 123 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
// Copyright (c) 2023 - 2026 Skip
// Licensed under the GNU Affero General Public License v3.0
// SPDX-License-Identifier: AGPL-3.0-only
/// Generate compiled Swift to Kotlin bridging code.
///
/// - Warning: This visitor assumes that the given syntax tree only contains bridged API.
final class KotlinBridgeToKotlinVisitor {
private let syntaxTree: KotlinSyntaxTree
private let options: KotlinBridgeOptions
private let translator: KotlinTranslator
private let codebaseInfo: CodebaseInfo.Context
private let includesUI: Bool
private var swiftDefinitions: [SwiftDefinition] = []
private var cdeclFunctions: [CDeclFunction] = []
private var needsObservationImport = false
init?(for syntaxTree: KotlinSyntaxTree, options: KotlinBridgeOptions, translator: KotlinTranslator) {
guard syntaxTree.isBridgeFile, !syntaxTree.root.isInIfSkipBlock, let codebaseInfo = translator.codebaseInfo else {
return nil
}
self.syntaxTree = syntaxTree
self.options = options
self.translator = translator
self.codebaseInfo = codebaseInfo
self.includesUI = translator.syntaxTree.root.statements.compactMap({ $0 as? ImportDeclaration }).contains { $0.modulePath.first == "SwiftUI" || $0.modulePath.first == "SkipSwiftUI" || $0.modulePath.first == "SkipFuseUI" }
}
func visit() -> [KotlinTransformerOutput] {
var globalFunctionCount = 0
var hasObservables = false
var hasSkipFuseImport = false
var nonKotlinImports: [KotlinStatement] = []
syntaxTree.root.visit { node in
if let importDeclaration = node as? KotlinImportDeclaration {
guard !importDeclaration.isInIfSkipBlock else {
return .skip
}
if importDeclaration.unmappedModulePath.first == "SkipFuse" {
hasSkipFuseImport = true
}
// Filter compiled-only imports from the transpiled output
if !isKotlinImport(importDeclaration) {
nonKotlinImports.append(importDeclaration)
}
return .skip
} else if let variableDeclaration = node as? KotlinVariableDeclaration {
if variableDeclaration.role == .global {
guard !variableDeclaration.isInIfSkipBlock else {
return .skip
}
update(variableDeclaration)
} else if variableDeclaration.extends != nil {
variableDeclaration.messages.append(.kotlinBridgeExtensionFunction(variableDeclaration, source: translator.syntaxTree.source))
}
return .skip
} else if let functionDeclaration = node as? KotlinFunctionDeclaration {
if functionDeclaration.role == .global {
guard !functionDeclaration.isInIfSkipBlock else {
return .skip
}
if update(functionDeclaration, uniquifier: globalFunctionCount) {
globalFunctionCount += 1
}
} else if functionDeclaration.extends != nil {
functionDeclaration.messages.append(.kotlinBridgeExtensionFunction(functionDeclaration, source: translator.syntaxTree.source))
}
return .skip
} else if let classDeclaration = node as? KotlinClassDeclaration {
guard !classDeclaration.isInIfSkipBlock else {
return .skip
}
update(classDeclaration)
hasObservables = hasObservables || classDeclaration.attributes.contains(.observable) || classDeclaration.unbridgedMembers.contains(where: { $0.isObservable })
return .recurse(nil)
} else if let interfaceDeclaration = node as? KotlinInterfaceDeclaration {
guard !interfaceDeclaration.isInIfSkipBlock else {
return .skip
}
if update(interfaceDeclaration) {
if let bridgeImpl = KotlinBridgeToSwiftVisitor.protocolBridgeImplDefinition(forProtocol: interfaceDeclaration.signature, inPackage: translator.packageName, statement: interfaceDeclaration, options: options, autoBridge: syntaxTree.autoBridge, codebaseInfo: codebaseInfo) {
swiftDefinitions.append(bridgeImpl)
}
}
return .recurse(nil)
} else if let codeBlock = node as? KotlinCodeBlock {
guard !codeBlock.isInIfSkipBlock else {
return .skip
}
hasObservables = hasObservables || codeBlock.unbridgedMembers.contains(where: { $0.isObservable })
return .recurse(nil)
} else {
return .recurse(nil)
}
}
nonKotlinImports.forEach { syntaxTree.root.remove(statement: $0) }
if hasObservables && !hasSkipFuseImport && !includesUI && (KotlinBridgeTransformer.testSkipAndroidBridge || codebaseInfo.global.needsAndroidBridge) {
syntaxTree.root.messages.append(.kotlinBridgeObservableMissingImport(syntaxTree.root, source: syntaxTree.source))
}
var outputs: [KotlinTransformerOutput] = []
if let bridgeOutput = bridgeOutput() {
outputs.append(bridgeOutput)
}
return outputs
}
private func bridgeOutput() -> KotlinTransformerOutput? {
guard !swiftDefinitions.isEmpty || !cdeclFunctions.isEmpty else {
return nil
}
guard let outputFile = syntaxTree.source.file.bridgeOutputFile else {
return nil
}
let importDeclarations: [ImportDeclaration] = translator.syntaxTree.root.statements.compactMap {
guard let importDeclaration = $0 as? ImportDeclaration else {
return nil
}
return importDeclaration.isInIfSkipBlock() ? nil : importDeclaration
}
let swiftDefinitions = self.swiftDefinitions
let cdeclFunctions = self.cdeclFunctions
let needsObservationImport = self.needsObservationImport
let outputNode = SwiftDefinition { output, indentation, _ in
output.append("import SkipBridge\n\n")
if needsObservationImport, !importDeclarations.contains(where: { $0.modulePath == ["Observation"] }) {
output.append("import Observation\n")
}
for importDeclaration in importDeclarations {
let path = importDeclaration.modulePath.joined(separator: ".")
output.append(indentation).append("import ").append(path).append("\n")
}
swiftDefinitions.forEach { $0.append(to: output, indentation: indentation) }
cdeclFunctions.forEach { $0.append(to: output, indentation: indentation) }
}
return KotlinTransformerOutput(file: outputFile, node: outputNode, type: .bridgeFromSwift)
}
private func isKotlinImport(_ importDeclaration: KotlinImportDeclaration) -> Bool {
guard !importDeclaration.isKotlinImport else {
return true
}
guard let moduleName = importDeclaration.modulePath.first else {
return false
}
guard CodebaseInfo.moduleNameMap[moduleName] == nil else {
return true
}
guard moduleName != codebaseInfo.global.moduleName else {
return true
}
return codebaseInfo.global.dependentModules.contains { moduleName == $0.moduleName && !$0.isEmpty }
}
@discardableResult private func update(_ variableDeclaration: KotlinVariableDeclaration, in classDeclaration: KotlinClassDeclaration? = nil, inExtensionOf interfaceDeclaration: KotlinInterfaceDeclaration? = nil) -> Bool {
guard !variableDeclaration.isGenerated else {
return false
}
guard let bridgable = variableDeclaration.checkBridgable(direction: .toKotlin, options: options, translator: translator) else {
return false
}
variableDeclaration.extras = Self.bridgeExtras(variableDeclaration.extras)
// If this is a let constant with a supported literal value, we'll re-declare rather than bridge it
guard !isSupportedConstant(variableDeclaration, type: bridgable.type) else {
return false
}
let propertyName = variableDeclaration.preEscapedPropertyName ?? variableDeclaration.propertyName
guard !variableDeclaration.isAppendAsFunction else {
let functionDeclaration = KotlinFunctionDeclaration(name: propertyName, sourceFile: variableDeclaration.sourceFile, sourceRange: variableDeclaration.sourceRange)
functionDeclaration.returnType = variableDeclaration.propertyType
functionDeclaration.role = variableDeclaration.role == .global ? .global : .member
functionDeclaration.modifiers = variableDeclaration.modifiers
functionDeclaration.attributes = variableDeclaration.attributes
functionDeclaration.apiFlags = variableDeclaration.apiFlags
functionDeclaration.parent = classDeclaration ?? interfaceDeclaration
let functionBridgable = FunctionBridgable(parameters: [], return: bridgable)
let (bodyCodeBlock, externalStatements) = addDefinitions(for: functionDeclaration, bridgable: functionBridgable, in: classDeclaration, inExtensionOf: interfaceDeclaration, isDeclaredByVariable: true)
variableDeclaration.getter = Accessor(body: bodyCodeBlock)
let parent = interfaceDeclaration?.parent ?? variableDeclaration.parent
(parent as? KotlinStatement)?.insert(statements: externalStatements, after: interfaceDeclaration ?? variableDeclaration)
return true
}
updateDeclaration(variableDeclaration, with: bridgable)
let externalName = "Swift_" + (interfaceDeclaration == nil ? "" : interfaceDeclaration!.name + "_") + (variableDeclaration.isStatic ? "Companion_" : "") + propertyName
var externalFunctionDeclarations: [String] = []
let (cdecl, cdeclName) = CDeclFunction.declaration(for: variableDeclaration, isCompanion: variableDeclaration.isStatic, name: externalName, translator: translator)
// Getter
let isInstance = classDeclaration != nil && !variableDeclaration.isStatic
let isProtocolInstance = interfaceDeclaration != nil && !variableDeclaration.isStatic
let classType = ClassType(classDeclaration)
let getterArguments: String
let getterParameters: String
if isInstance, let classType {
getterArguments = "(\(classType.peerExternalArgument))"
getterParameters = "(\(classType.peerExternalParameter))"
} else if isProtocolInstance, let interfaceDeclaration {
getterArguments = "(this)"
getterParameters = "(Java_iface: \(interfaceDeclaration.name))"
} else {
getterArguments = "()"
getterParameters = "()"
}
let getterSref: String
if let onUpdate = variableDeclaration.onUpdate?(), !onUpdate.isEmpty, !options.contains(.kotlincompat) {
getterSref = ".sref(\(onUpdate))"
} else {
getterSref = ""
}
var asOptional = bridgable.type.isOptional
var forceUnwrapString = ""
if variableDeclaration.apiFlags.throwsType != .none && !bridgable.type.isOptional {
asOptional = true
forceUnwrapString = "!!"
}
let castString = bridgable.genericType == nil ? "" : " as \(bridgable.kotlinType.kotlin)"
let getterBody: [String]
if bridgable.genericType == nil {
getterBody = [
"return \(externalName)\(getterArguments)\(forceUnwrapString)\(getterSref)"
]
} else {
getterBody = [
"return (\(externalName)\(getterArguments)\(forceUnwrapString)\(castString))\(getterSref)"
]
}
variableDeclaration.getter = Accessor(body: KotlinCodeBlock(statements: getterBody.map { KotlinRawStatement(sourceCode: $0) }))
externalFunctionDeclarations.append("private external fun \(externalName)\(getterParameters): \(bridgable.externalType.asOptional(asOptional).kotlin)")
let cdeclInstanceParameters: [TypeSignature.Parameter]
var cdeclGetterBody: [String] = []
let valueString: String
let optionsString = options.jconvertibleOptions
if let classDeclaration {
if isInstance, let classType {
cdeclInstanceParameters = [classType.peerSwiftParameter]
cdeclGetterBody.append(0, classType.peerSwiftAssignment(to: classDeclaration, optionsString: optionsString))
switch classType {
case .generic:
valueString = bridgable.type.convertToCDecl(value: "peer_swift.get_\(propertyName)()", strategy: bridgable.strategy, options: options)
default:
valueString = bridgable.type.convertToCDecl(value: "\(classType.peerSwiftTarget).\(propertyName)", strategy: bridgable.strategy, options: options)
}
} else {
cdeclInstanceParameters = []
valueString = bridgable.type.convertToCDecl(value: "\(classDeclaration.signature).\(propertyName)", strategy: bridgable.strategy, options: options)
}
} else if let interfaceDeclaration {
if isProtocolInstance {
cdeclInstanceParameters = [TypeSignature.Parameter(label: "Java_iface", type: .javaObjectPointer)]
cdeclGetterBody.append("let peer_swift = AnyBridging.fromJavaObject(Java_iface, options: \(optionsString)) as! any \(interfaceDeclaration.name)")
valueString = bridgable.type.convertToCDecl(value: "peer_swift.\(propertyName)", strategy: bridgable.strategy, options: options)
} else {
cdeclInstanceParameters = []
valueString = bridgable.type.convertToCDecl(value: "\(interfaceDeclaration.name).\(propertyName)", strategy: bridgable.strategy, options: options)
}
} else {
cdeclInstanceParameters = []
valueString = bridgable.type.convertToCDecl(value: propertyName, strategy: bridgable.strategy, options: options)
}
if variableDeclaration.apiFlags.throwsType == .none {
variableDeclaration.appendMainActorIsolated(&cdeclGetterBody, in: classDeclaration, isReturn: true) { body, indentation in
body.append(indentation, "return " + valueString)
}
} else {
cdeclGetterBody.append("do {")
variableDeclaration.appendMainActorIsolated(&cdeclGetterBody, 1, in: classDeclaration, isReturn: true) { body, indentation in
body.append(indentation, "let f_return_swift = try " + valueString)
body.append(indentation, "return f_return_swift.toJavaObject(options: \(optionsString))")
}
cdeclGetterBody.append("} catch {")
cdeclGetterBody.append(1, "JThrowable.throw(error, options: \(optionsString), env: Java_env)")
cdeclGetterBody.append(1, "return nil")
cdeclGetterBody.append("}")
}
let cdeclGetter = CDeclFunction(name: cdeclName, cdecl: cdecl, signature: .function(cdeclInstanceParameters, bridgable.type.asOptional(asOptional).cdecl(strategy: bridgable.strategy, options: options), APIFlags(), nil), body: cdeclGetterBody)
cdeclFunctions.append(cdeclGetter)
// Setter
if variableDeclaration.apiFlags.options.contains(.writeable) {
let castString = bridgable.genericType == nil ? "" : " as \(TypeSignature.any.asOptional(bridgable.type.isOptional).kotlin)"
let setterArguments: String
let setterInstanceParameter: String
if isInstance {
setterArguments = "\(classType?.peerExternalArgument ?? ""), newValue\(castString)"
setterInstanceParameter = "\(classType?.peerExternalParameter ?? ""), "
} else if isProtocolInstance {
setterArguments = "this, newValue\(castString)"
setterInstanceParameter = "Java_iface: \(interfaceDeclaration!.name), "
} else {
setterArguments = "newValue\(castString)"
setterInstanceParameter = ""
}
let setterBody = [
externalName + "_set(" + setterArguments + ")"
]
variableDeclaration.setter = Accessor(parameterName: "newValue", body: KotlinCodeBlock(statements: setterBody.map { KotlinRawStatement(sourceCode: $0) }))
if let annotation = variableDeclaration.preventJVMNameManglingAnnotation(name: externalName + "_set", isFunction: true) {
externalFunctionDeclarations.append(annotation)
}
externalFunctionDeclarations.append("private external fun \(externalName)_set(\(setterInstanceParameter)value: \(bridgable.externalType.kotlin))")
var cdeclSetterBody: [String] = []
let setValueString: String
if let classDeclaration, let classType {
if isInstance {
cdeclSetterBody.append(0, classType.peerSwiftAssignment(to: classDeclaration, optionsString: optionsString))
switch classType {
case .generic:
setValueString = "peer_swift.set_\(propertyName)(" + bridgable.constrainedType.convertFromCDecl(value: "value", strategy: bridgable.strategy, options: options) + ")"
default:
setValueString = "\(classType.peerSwiftTarget).\(propertyName) = " + bridgable.constrainedType.convertFromCDecl(value: "value", strategy: bridgable.strategy, options: options)
}
} else {
setValueString = "\(classDeclaration.signature).\(propertyName) = " + bridgable.constrainedType.convertFromCDecl(value: "value", strategy: bridgable.strategy, options: options)
}
} else if let interfaceDeclaration {
if isProtocolInstance {
cdeclSetterBody.append("let peer_swift = AnyBridging.fromJavaObject(Java_iface, options: \(optionsString)) as! any \(interfaceDeclaration.name)")
setValueString = "peer_swift.\(propertyName) = " + bridgable.constrainedType.convertFromCDecl(value: "value", strategy: bridgable.strategy, options: options)
} else {
setValueString = "\(interfaceDeclaration.name).\(propertyName) = " + bridgable.constrainedType.convertFromCDecl(value: "value", strategy: bridgable.strategy, options: options)
}
} else {
setValueString = propertyName + " = " + bridgable.constrainedType.convertFromCDecl(value: "value", strategy: bridgable.strategy, options: options)
}
let cdeclParameter = TypeSignature.Parameter(label: "value", type: bridgable.type.cdecl(strategy: bridgable.strategy, options: options))
variableDeclaration.appendMainActorIsolated(&cdeclSetterBody, in: classDeclaration, parameter: cdeclParameter) { body, indentation in
body.append(indentation, setValueString)
}
let cdeclSetter = CDeclFunction(name: cdeclName + "_set", cdecl: cdecl + "_1set", signature: .function(cdeclInstanceParameters + [cdeclParameter], .void, APIFlags(), nil), body: cdeclSetterBody)
cdeclFunctions.append(cdeclSetter)
}
variableDeclaration.willSet = nil
variableDeclaration.didSet = nil
// Add function declarations to transpiled output
let parent = interfaceDeclaration?.parent ?? variableDeclaration.parent
(parent as? KotlinStatement)?.insert(statements: externalFunctionDeclarations.map { KotlinRawStatement(sourceCode: $0, isStatic: variableDeclaration.isStatic) }, after: interfaceDeclaration ?? variableDeclaration)
return true
}
private func updateDeclaration(_ variableDeclaration: KotlinVariableDeclaration, with bridgable: Bridgable) {
// Remove initial value and make sure type is declared
variableDeclaration.value = nil
variableDeclaration.declaredType = bridgable.kotlinType
}
private func isSupportedConstant(_ variableDeclaration: KotlinVariableDeclaration, type: TypeSignature) -> Bool {
guard variableDeclaration.isLet, let value = variableDeclaration.value else {
return false
}
guard !(value is KotlinNullLiteral) else {
return true
}
// Only support constants whose values we can mirror in Kotlin without workarounds from the user. For
// example we don't support Floats because Kotlin requires Float(value)
switch type.asOptional(false) {
case .bool:
return variableDeclaration.value?.type == .booleanLiteral
case .double, .int, .int32:
return variableDeclaration.value?.type == .numericLiteral
case .string:
guard let stringLiteral = variableDeclaration.value as? KotlinStringLiteral else {
return false
}
return !stringLiteral.segments.contains { $0.isExpression }
default:
return false
}
}
private func update(_ functionDeclaration: KotlinFunctionDeclaration, in classDeclaration: KotlinClassDeclaration? = nil, isBridgedSubclass: Bool = false, inExtensionOf interfaceDeclaration: KotlinInterfaceDeclaration? = nil, uniquifier: Int) -> Bool {
guard !functionDeclaration.isGenerated || functionDeclaration.type == .constructorDeclaration else {
return false
}
let isMutableStructCopyConstructor = classDeclaration != nil && functionDeclaration.isMutableStructCopyConstructor
let bridgable: FunctionBridgable
if isMutableStructCopyConstructor {
let parameterBridgable = Bridgable(type: .named("MutableStruct", []), kotlinType: .module("Swift", .named("MutableStruct", [])), genericType: nil, strategy: .peer)
bridgable = FunctionBridgable(parameters: [parameterBridgable], return: Bridgable(type: .void, kotlinType: .void, genericType: nil, strategy: .direct))
} else {
guard let functionBridgable = functionDeclaration.checkBridgable(direction: .toKotlin, options: options, translator: translator) else {
return false
}
bridgable = functionBridgable
}
updateDeclaration(functionDeclaration, with: bridgable)
functionDeclaration.extras = Self.bridgeExtras(functionDeclaration.extras)
let (bodyCodeBlock, externalStatements) = addDefinitions(for: functionDeclaration, bridgable: bridgable, in: classDeclaration, isBridgedSubclass: isBridgedSubclass, inExtensionOf: interfaceDeclaration, isMutableStructCopyConstructor: isMutableStructCopyConstructor, uniquifier: uniquifier)
functionDeclaration.body = bodyCodeBlock
let parent = interfaceDeclaration?.parent ?? functionDeclaration.parent
(parent as? KotlinStatement)?.insert(statements: externalStatements, after: interfaceDeclaration ?? functionDeclaration)
return true
}
private func updateDeclaration(_ functionDeclaration: KotlinFunctionDeclaration, with bridgable: FunctionBridgable) {
functionDeclaration.returnType = bridgable.return.kotlinType
functionDeclaration.parameters = functionDeclaration.parameters.enumerated().map { index, parameter in
var parameter = parameter
parameter.declaredType = bridgable.parameters[index].kotlinType
return parameter
}
functionDeclaration.generics = functionDeclaration.generics.compactMapBridgable(direction: .toKotlin, options: options, codebaseInfo: codebaseInfo)
}
private func addDefinitions(for functionDeclaration: KotlinFunctionDeclaration, bridgable: FunctionBridgable, in classDeclaration: KotlinClassDeclaration? = nil, isBridgedSubclass: Bool = false, inExtensionOf interfaceDeclaration: KotlinInterfaceDeclaration? = nil, isMutableStructCopyConstructor: Bool = false, isDeclaredByVariable: Bool = false, uniquifier: Int? = nil) -> (KotlinCodeBlock, [KotlinStatement]) {
let functionName = functionDeclaration.preEscapedName ?? functionDeclaration.name
let isAsync = functionDeclaration.apiFlags.options.contains(.async)
let isThrows = functionDeclaration.apiFlags.throwsType != .none
let isCompanionCall = functionDeclaration.isStatic || (functionDeclaration.type == .constructorDeclaration && isBridgedSubclass)
let externalName = (isAsync ? "Swift_callback_" : "Swift_") + (interfaceDeclaration == nil ? "" : interfaceDeclaration!.name + "_") + (isCompanionCall ? "Companion_" : "") + functionName + (uniquifier == nil ? "" : "_\(uniquifier!)")
var cdeclBodyParameters: [String] = []
if !isMutableStructCopyConstructor || classDeclaration?.generics.isEmpty != false {
for index in 0..<bridgable.parameters.count {
let strategy = bridgable.parameters[index].strategy
let parameterType = isMutableStructCopyConstructor ? classDeclaration!.signature : bridgable.parameters[index].constrainedType
cdeclBodyParameters.append("let p_\(index)_swift = " + parameterType.convertFromCDecl(value: "p_\(index)", strategy: strategy, options: options))
}
}
var cdeclBody: [String] = []
if isAsync {
let callbackType = bridgable.return.constrainedType.callbackClosureType(apiFlags: functionDeclaration.apiFlags, kotlin: false)
cdeclBody.append("let f_callback_swift = " + callbackType.convertFromCDecl(value: "f_callback", strategy: .direct, options: options))
}
let classType = ClassType(classDeclaration)
let swiftCallTarget: String
var externalArgumentsString: String
var swiftFunctionName = functionName
let optionsString = options.jconvertibleOptions
if let classDeclaration, let classType, functionDeclaration.type != .constructorDeclaration {
if functionDeclaration.isStatic {
swiftCallTarget = classDeclaration.name + "."
externalArgumentsString = ""
} else {
cdeclBody.append(0, classType.peerSwiftAssignment(to: classDeclaration, optionsString: optionsString))
swiftCallTarget = classType.peerSwiftTarget + "."
externalArgumentsString = classType.peerExternalArgument
if classType == .generic {
swiftFunctionName += uniquifier == nil ? "" : "_\(uniquifier!)"
}
}
} else if let interfaceDeclaration {
if functionDeclaration.isStatic {
swiftCallTarget = interfaceDeclaration.name + "."
externalArgumentsString = ""
} else {
cdeclBody.append("let peer_swift = AnyBridging.fromJavaObject(Java_iface, options: \(optionsString)) as! any \(interfaceDeclaration.name)")
swiftCallTarget = "peer_swift."
externalArgumentsString = "this"
}
} else {
swiftCallTarget = ""
externalArgumentsString = ""
}
if !functionDeclaration.parameters.isEmpty {
if !externalArgumentsString.isEmpty {
externalArgumentsString += ", "
}
externalArgumentsString += zip(functionDeclaration.parameters, bridgable.parameters).enumerated().map { index, zipped in
let parameter = zipped.0
let bridgable = zipped.1
let label = parameter.internalLabel == "_" ? "p\(index)" : parameter.internalLabel
return bridgable.genericType == nil ? label : "\(label) as \(TypeSignature.any.asOptional(bridgable.type.isOptional).kotlin)"
}.joined(separator: ", ")
}
let swiftArgumentsString: String
if isDeclaredByVariable {
swiftArgumentsString = ""
} else {
swiftArgumentsString = "(" + functionDeclaration.parameters.enumerated().map { index, parameter in
let swiftArgument = "p_\(index)_swift"
if !isMutableStructCopyConstructor, classDeclaration?.generics.isEmpty != false, let externalLabel = functionDeclaration.preEscapedParameterLabels?[index] ?? parameter.externalLabel {
return externalLabel + ": " + swiftArgument
} else {
return swiftArgument
}
}.joined(separator: ", ") + ")"
}
var body: [String] = []
let cdeclReturnType: TypeSignature
let cdeclParameters = bridgable.parameters.enumerated().map { (index, bridgable) in
let strategy = bridgable.strategy
return TypeSignature.Parameter(label: "p_\(index)", type: bridgable.type.cdecl(strategy: strategy, options: options))
}
if let classDeclaration, functionDeclaration.type == .constructorDeclaration {
if isBridgedSubclass {
functionDeclaration.delegatingConstructorCall = KotlinRawExpression(sourceCode: "super(Swift_peer = \(externalName)(\(externalArgumentsString)), marker = null)")
} else {
body.append("Swift_peer = \(externalName)(\(externalArgumentsString))")
}
if isThrows {
cdeclBody.append("do {")
functionDeclaration.appendMainActorIsolated(&cdeclBody, 1, in: classDeclaration, parameters: cdeclParameters, isReturn: true) { body, indentation in
body.append(indentation, cdeclBodyParameters)
if classType == .reference {
body.append(indentation, "let f_return_swift = try \(classDeclaration.signature)\(swiftArgumentsString)")
} else {
body.append(indentation, "let f_return_swift = try SwiftValueTypeBox(\(classDeclaration.signature)\(swiftArgumentsString))")
}
body.append(indentation, "return SwiftObjectPointer.pointer(to: f_return_swift, retain: true)")
}
cdeclBody.append("} catch {")
cdeclBody.append(1, "JThrowable.throw(error, options: \(optionsString), env: Java_env)")
cdeclBody.append(1, "return SwiftObjectNil")
cdeclBody.append("}")
} else {
functionDeclaration.appendMainActorIsolated(&cdeclBody, in: classDeclaration, parameters: cdeclParameters, isReturn: true) { body, indentation in
body.append(indentation, cdeclBodyParameters)
if classType == .reference {
body.append(indentation, "let f_return_swift = \(classDeclaration.signature)\(swiftArgumentsString)")
} else if isMutableStructCopyConstructor && classType == .generic {
// Create a new type-erased wrapper using the original instance
body.append(indentation, "let ptr = SwiftObjectPointer.peer(of: p_0, options: \(optionsString))")
body.append(indentation, "let peer_swift: \(classDeclaration.signature.typeErasedClass) = ptr.pointee()!")
body.append(indentation, "let f_return_swift = (peer_swift.genericvalue as! TypeErasedConvertible).toTypeErased()")
} else if isMutableStructCopyConstructor {
body.append(indentation, "let f_return_swift = SwiftValueTypeBox\(swiftArgumentsString)")
} else {
body.append(indentation, "let f_return_swift = SwiftValueTypeBox(\(classDeclaration.signature)\(swiftArgumentsString))")
}
body.append(indentation, "return SwiftObjectPointer.pointer(to: f_return_swift, retain: true)")
}
}
cdeclReturnType = .swiftObjectPointer(kotlin: false)
} else if isAsync {
let castString = bridgable.return.genericType == nil ? "" : " as \(bridgable.return.kotlinType.kotlin)"
body.append("kotlin.coroutines.suspendCoroutine { f_continuation ->")
if isThrows {
if bridgable.return.type == .void {
body.append(1, externalName + "(\(externalArgumentsString)) { f_error ->")
} else {
body.append(1, externalName + "(\(externalArgumentsString)) { f_return, f_error ->")
}
body.append(2, "if (f_error != null) {")
body.append(3, "f_continuation.resumeWith(kotlin.Result.failure(f_error))")
body.append(2, "} else {")
if bridgable.return.type == .void {
body.append(3, "f_continuation.resumeWith(kotlin.Result.success(Unit))")
} else {
let forceUnwrapString = bridgable.return.type.isOptional ? "" : "!!"
body.append(3, "f_continuation.resumeWith(kotlin.Result.success(f_return\(forceUnwrapString)\(castString)))")
}
body.append(2, "}")
} else {
if bridgable.return.type == .void {
body.append(1, externalName + "(\(externalArgumentsString)) {")
body.append(2, "f_continuation.resumeWith(kotlin.Result.success(Unit))")
} else {
body.append(1, externalName + "(\(externalArgumentsString)) { f_return ->")
body.append(2, "f_continuation.resumeWith(kotlin.Result.success(f_return\(castString)))")
}
}
body.append(1, "}")
body.append("}")
cdeclBody += cdeclBodyParameters
cdeclBody.append("Task {")
if isThrows {
cdeclBody.append(1, "do {")
if bridgable.return.type == .void {
cdeclBody.append(2, "try await \(swiftCallTarget)\(swiftFunctionName)\(swiftArgumentsString)")
cdeclBody.append(2, "f_callback_swift(nil)")
} else {
cdeclBody.append(2, "let f_return_swift = try await \(swiftCallTarget)\(swiftFunctionName)\(swiftArgumentsString)")
cdeclBody.append(2, "f_callback_swift(f_return_swift, nil)")
}
cdeclBody.append(1, "} catch {")
cdeclBody.append(2, "jniContext {")
if bridgable.return.type == .void {
cdeclBody.append(3, "f_callback_swift(JThrowable.toThrowable(error, options: \(optionsString))!)")
} else {
cdeclBody.append(3, "f_callback_swift(nil, JThrowable.toThrowable(error, options: \(optionsString))!)")
}
cdeclBody.append(2, "}")
cdeclBody.append(1, "}")
} else if bridgable.return.type == .void {
cdeclBody.append(1, "await \(swiftCallTarget)\(swiftFunctionName)\(swiftArgumentsString)")
cdeclBody.append(1, "f_callback_swift()")
} else {
cdeclBody.append(1, "let f_return_swift = await \(swiftCallTarget)\(swiftFunctionName)\(swiftArgumentsString)")
cdeclBody.append(1, "f_callback_swift(f_return_swift)")
}
cdeclBody.append("}")
cdeclReturnType = .void
} else if bridgable.return.type == .void {
body.append(externalName + "(\(externalArgumentsString))")
if isThrows {
cdeclBody.append("do {")
functionDeclaration.appendMainActorIsolated(&cdeclBody, 1, in: classDeclaration, parameters: cdeclParameters) { body, indentation in
body.append(indentation, cdeclBodyParameters)
body.append(indentation, "try \(swiftCallTarget)\(swiftFunctionName)\(swiftArgumentsString)")
}
cdeclBody.append("} catch {")
cdeclBody.append(1, "JThrowable.throw(error, options: \(optionsString), env: Java_env)")
cdeclBody.append("}")
} else {
functionDeclaration.appendMainActorIsolated(&cdeclBody, in: classDeclaration, parameters: cdeclParameters) { body, indentation in
body.append(indentation, cdeclBodyParameters)
body.append(indentation, "\(swiftCallTarget)\(swiftFunctionName)\(swiftArgumentsString)")
}
}
cdeclReturnType = .void
} else {
let forceUnwrapString: String
if isThrows {
forceUnwrapString = bridgable.return.type.isOptional ? "" : "!!"
cdeclBody.append("do {")
functionDeclaration.appendMainActorIsolated(&cdeclBody, 1, in: classDeclaration, parameters: cdeclParameters, isReturn: true) { body, indentation in
body.append(indentation, cdeclBodyParameters)
body.append(indentation, "let f_return_swift = try \(swiftCallTarget)\(swiftFunctionName)\(swiftArgumentsString)")
body.append(indentation, "return " + bridgable.return.type.asOptional(true).convertToCDecl(value: "f_return_swift", strategy: bridgable.return.strategy, options: options))
}
cdeclBody.append("} catch {")
cdeclBody.append(1, "JThrowable.throw(error, options: \(optionsString), env: Java_env)")
cdeclBody.append(1, "return nil")
cdeclBody.append("}")
cdeclReturnType = bridgable.return.type.asOptional(true).cdecl(strategy: bridgable.return.strategy, options: options)
} else {
forceUnwrapString = ""
functionDeclaration.appendMainActorIsolated(&cdeclBody, in: classDeclaration, parameters: cdeclParameters, isReturn: true) { body, indentation in
body.append(indentation, cdeclBodyParameters)
body.append(indentation, "let f_return_swift = \(swiftCallTarget)\(swiftFunctionName)\(swiftArgumentsString)")
body.append(indentation, "return " + functionDeclaration.returnType.convertToCDecl(value: "f_return_swift", strategy: bridgable.return.strategy, options: options))
}
cdeclReturnType = bridgable.return.type.cdecl(strategy: bridgable.return.strategy, options: options)
}
let castString = bridgable.return.genericType == nil ? "" : " as \(bridgable.return.kotlinType.kotlin)"
body.append("return \(externalName)(\(externalArgumentsString))\(forceUnwrapString)\(castString)")
}
var externalFunctionDeclaration = "private external fun \(externalName)("
var externalParametersString: String
if let classType, functionDeclaration.type != .constructorDeclaration && !functionDeclaration.isStatic {
externalParametersString = classType.peerExternalParameter
} else if let interfaceDeclaration, !functionDeclaration.isStatic {
externalParametersString = "Java_iface: \(interfaceDeclaration.name)"
} else {
externalParametersString = ""
}
if !functionDeclaration.parameters.isEmpty {
if !externalParametersString.isEmpty {
externalParametersString += ", "
}
externalParametersString += functionDeclaration.parameters.enumerated().map { index, parameter in
let label = parameter.internalLabel == "_" ? "p\(index)" : parameter.internalLabel
return label + ": " + bridgable.parameters[index].externalType.kotlin
}.joined(separator: ", ")
}
if isAsync {
if !externalParametersString.isEmpty {
externalParametersString += ", "
}
externalParametersString += "f_callback: " + bridgable.return.externalType.callbackClosureType(apiFlags: functionDeclaration.apiFlags, kotlin: true).kotlin
}
externalFunctionDeclaration += externalParametersString
externalFunctionDeclaration += ")"
if functionDeclaration.type == .constructorDeclaration {
externalFunctionDeclaration += ": skip.bridge.SwiftObjectPointer"
} else if bridgable.return.type != .void && !isAsync {
var returnType: TypeSignature = bridgable.return.externalType
if functionDeclaration.apiFlags.throwsType != .none {
returnType = returnType.asOptional(true)
}
externalFunctionDeclaration += ": " + returnType.kotlin
}
var externalFunctionDeclarations: [String] = [externalFunctionDeclaration]
if let annotation = functionDeclaration.preventJVMNameManglingAnnotation(name: externalName) {
externalFunctionDeclarations.insert(annotation, at: 0)
}
let (cdecl, cdeclName) = CDeclFunction.declaration(for: functionDeclaration, isCompanion: isCompanionCall, name: externalName, translator: translator)
let instanceParameter: [TypeSignature.Parameter]
if let classType, functionDeclaration.type != .constructorDeclaration && !functionDeclaration.isStatic { instanceParameter = [classType.peerSwiftParameter]
} else if interfaceDeclaration != nil, !functionDeclaration.isStatic {
instanceParameter = [TypeSignature.Parameter(label: "Java_iface", type: .javaObjectPointer)]
} else {
instanceParameter = []
}
let callbackParameter = isAsync ? [TypeSignature.Parameter(label: "f_callback", type: .javaObjectPointer)] : []
let cdeclType: TypeSignature = .function(instanceParameter + cdeclParameters + callbackParameter, cdeclReturnType, APIFlags(), nil)
let cdeclFunction = CDeclFunction(name: cdeclName, cdecl: cdecl, signature: cdeclType, body: cdeclBody)
cdeclFunctions.append(cdeclFunction)
let bodyCodeBlock = KotlinCodeBlock(statements: body.map { KotlinRawStatement(sourceCode: $0) })
let externalStatements = externalFunctionDeclarations.map { KotlinRawStatement(sourceCode: $0, isStatic: isCompanionCall) }
return (bodyCodeBlock, externalStatements)
}
private func isGeneratedMemberwiseConstructor(_ functionDeclaration: KotlinFunctionDeclaration, for classDeclaration: KotlinClassDeclaration?) -> Bool {
guard let classDeclaration, classDeclaration.declarationType == .structDeclaration, functionDeclaration.type == .constructorDeclaration else {
return false
}
guard functionDeclaration.parameters.count != 1 || !functionDeclaration.parameters[0].declaredType.isNamed("MutableStruct") else {
return false
}
return true
}
private func updateEqualsDeclaration(_ functionDeclaration: KotlinFunctionDeclaration, in classDeclaration: KotlinClassDeclaration) {
functionDeclaration.extras = Self.bridgeExtras(functionDeclaration.extras)
let classWithAnyGenerics = classDeclaration.signature.withGenerics(of: .any)
let bodySourceCode: [String]
if functionDeclaration.isKotlinEqualImplementation {
// equals(other:)
bodySourceCode = [
"if (other === this) return true",
"if (other !is \(classWithAnyGenerics.kotlin)) return false",
"return Swift_isequal(this, other)"
]
} else {
// ==(lhs:, rhs:)
bodySourceCode = ["return Swift_isequal(lhs, rhs)"]
}
functionDeclaration.body = KotlinCodeBlock(statements: bodySourceCode.map { KotlinRawStatement(sourceCode: $0) })
let externalFunctionDeclaration = KotlinRawStatement(sourceCode: "private external fun Swift_isequal(lhs: \(classWithAnyGenerics), rhs: \(classWithAnyGenerics)): Boolean")
classDeclaration.insert(statements: [externalFunctionDeclaration], after: functionDeclaration)
let (cdecl, cdeclName) = CDeclFunction.declaration(for: functionDeclaration, isCompanion: false, name: "Swift_isequal", translator: translator)
let cdeclType: TypeSignature = .function([TypeSignature.Parameter(label: "lhs", type: .javaObjectPointer), TypeSignature.Parameter(label: "rhs", type: .javaObjectPointer)], .bool, APIFlags(), nil)
var cdeclBody: [String]
let retString: String
if !classDeclaration.generics.isEmpty {
cdeclBody = [
"let lhs_swift: \(classDeclaration.signature.typeErasedClass) = lhs.pointee()!",
"let rhs_swift: \(classDeclaration.signature.typeErasedClass) = rhs.pointee()!"
]
retString = "return lhs_swift.isequal(rhs_swift)"
} else {
cdeclBody = [
"let lhs_swift = \(classDeclaration.signature).fromJavaObject(lhs, options: \(options.jconvertibleOptions))",
"let rhs_swift = \(classDeclaration.signature).fromJavaObject(rhs, options: \(options.jconvertibleOptions))"
]
retString = "return lhs_swift == rhs_swift"
}
functionDeclaration.appendMainActorIsolated(&cdeclBody, in: classDeclaration, isReturn: true) { body, indentation in
body.append(indentation, retString)
}
let cdeclFunction = CDeclFunction(name: cdeclName, cdecl: cdecl, signature: cdeclType, body: cdeclBody)
cdeclFunctions.append(cdeclFunction)
}
private func defaultEqualsDeclaration(for classDeclaration: KotlinClassDeclaration) -> ([KotlinStatement], CDeclFunction?) {
let equals = KotlinFunctionDeclaration(name: "equals")
equals.parameters = [Parameter<KotlinExpression>(externalLabel: "other", declaredType: .optional(.any))]
equals.returnType = .bool
equals.modifiers.visibility = .public
equals.modifiers.isOverride = true
equals.ensureLeadingNewlines(1)
equals.isGenerated = true
equals.parent = classDeclaration
let statements: [KotlinStatement]
let sourceCode: [String]
let cdeclFunction: CDeclFunction?
if !classDeclaration.generics.isEmpty, classDeclaration.declarationType == .classDeclaration || classDeclaration.declarationType == .actorDeclaration {
let externalFunctionDeclaration = KotlinRawStatement(sourceCode: "private external fun Swift_isequal(lhs: skip.bridge.SwiftObjectPointer, rhs: skip.bridge.SwiftObjectPointer): Boolean")
statements = [equals, externalFunctionDeclaration]
sourceCode = [
"if (other !is skip.bridge.SwiftPeerBridged) return false",
"return Swift_isequal(Swift_peer, other.Swift_peer())"
]
let (cdecl, cdeclName) = CDeclFunction.declaration(for: equals, isCompanion: false, name: "Swift_isequal", translator: translator)
let cdeclType: TypeSignature = .function([TypeSignature.Parameter(label: "lhs", type: .swiftObjectPointer(kotlin: false)), TypeSignature.Parameter(label: "rhs", type: .swiftObjectPointer(kotlin: false))], .bool, APIFlags(), nil)
cdeclFunction = CDeclFunction(name: cdeclName, cdecl: cdecl, signature: cdeclType, body: [
"let lhs_swift: \(classDeclaration.signature.typeErasedClass) = lhs.pointee()!",
"let rhs_swift: \(classDeclaration.signature.typeErasedClass) = rhs.pointee()!",
"return lhs_swift.genericptr == rhs_swift.genericptr"
])
} else {
statements = [equals]
sourceCode = [
"if (other !is skip.bridge.SwiftPeerBridged) return false",
"return Swift_peer == other.Swift_peer()"
]
cdeclFunction = nil
}
equals.body = KotlinCodeBlock(statements: sourceCode.map { KotlinRawStatement(sourceCode: $0) })
return (statements, cdeclFunction)
}
private func updateHashDeclaration(_ functionDeclaration: KotlinFunctionDeclaration, in classDeclaration: KotlinClassDeclaration) {
functionDeclaration.extras = Self.bridgeExtras(functionDeclaration.extras)
let bodySourceCode: [String]
if functionDeclaration.isKotlinHashImplementation {
// hashCode()
bodySourceCode = ["return Swift_hashvalue(Swift_peer).hashCode()"]
} else {
// hash(into:)
bodySourceCode = ["hasher.value.combine(Swift_hashvalue(Swift_peer))"]
}
functionDeclaration.body = KotlinCodeBlock(statements: bodySourceCode.map { KotlinRawStatement(sourceCode: $0) })
let externalFunctionDeclaration = KotlinRawStatement(sourceCode: "private external fun Swift_hashvalue(Swift_peer: skip.bridge.SwiftObjectPointer): Long")
classDeclaration.insert(statements: [externalFunctionDeclaration], after: functionDeclaration)
let classType = ClassType(classDeclaration)
let (cdecl, cdeclName) = CDeclFunction.declaration(for: functionDeclaration, isCompanion: false, name: "Swift_hashvalue", translator: translator)
let cdeclType: TypeSignature = .function([classType.peerSwiftParameter], .int64, APIFlags(), nil)
var cdeclBody = classType.peerSwiftAssignment(to: classDeclaration, optionsString: "[]")
functionDeclaration.appendMainActorIsolated(&cdeclBody, in: classDeclaration, isReturn: true) { body, indentation in
switch classType {
case .generic:
body.append(indentation, "return Int64((\(classType.peerSwiftTarget).genericvalue as! (any Hashable)).hashValue)")
default:
body.append(indentation, "return Int64(\(classType.peerSwiftTarget).hashValue)")
}
}
let cdeclFunction = CDeclFunction(name: cdeclName, cdecl: cdecl, signature: cdeclType, body: cdeclBody)
cdeclFunctions.append(cdeclFunction)
}
private func defaultHashDeclaration(for classDeclaration: KotlinClassDeclaration) -> ([KotlinStatement], CDeclFunction?) {
let hash = KotlinFunctionDeclaration(name: "hashCode")
hash.returnType = .int
hash.modifiers.visibility = .public
hash.modifiers.isOverride = true
hash.ensureLeadingNewlines(1)
hash.isGenerated = true
hash.parent = classDeclaration
let classType = ClassType(classDeclaration)
let statements: [KotlinStatement]
let sourceCode: [String]
let cdeclFunction: CDeclFunction?
if classType == .generic, classDeclaration.declarationType == .classDeclaration || classDeclaration.declarationType == .actorDeclaration {
let externalFunctionDeclaration = KotlinRawStatement(sourceCode: "private external fun Swift_hashvalue(Swift_peer: skip.bridge.SwiftObjectPointer): Long")
statements = [hash, externalFunctionDeclaration]
sourceCode = ["return Swift_hashvalue(Swift_peer).hashCode()"]
let (cdecl, cdeclName) = CDeclFunction.declaration(for: hash, isCompanion: false, name: "Swift_hashvalue", translator: translator)
let cdeclType: TypeSignature = .function([classType.peerSwiftParameter], .int64, APIFlags(), nil)
cdeclFunction = CDeclFunction(name: cdeclName, cdecl: cdecl, signature: cdeclType, body: [
"let peer_swift: \(classDeclaration.signature.typeErasedClass) = Swift_peer.pointee()!",
"return Int64(peer_swift.genericptr.hashValue)"
])
} else {
statements = [hash]
sourceCode = ["return Swift_peer.hashCode()"]
cdeclFunction = nil
}
hash.body = KotlinCodeBlock(statements: sourceCode.map { KotlinRawStatement(sourceCode: $0) })
return (statements, cdeclFunction)
}
private func updateLessThanDeclaration(_ functionDeclaration: KotlinFunctionDeclaration, in classDeclaration: KotlinClassDeclaration) {
functionDeclaration.extras = Self.bridgeExtras(functionDeclaration.extras)
functionDeclaration.body = KotlinCodeBlock(statements: [
"return Swift_islessthan(lhs, rhs)"
].map { KotlinRawStatement(sourceCode: $0) })
let externalFunctionDeclaration = KotlinRawStatement(sourceCode: "private external fun Swift_islessthan(lhs: \(classDeclaration.signature), rhs: \(classDeclaration.signature)): Boolean")
classDeclaration.insert(statements: [externalFunctionDeclaration], after: functionDeclaration)
let (cdecl, cdeclName) = CDeclFunction.declaration(for: functionDeclaration, isCompanion: false, name: "Swift_islessthan", translator: translator)
let cdeclType: TypeSignature = .function([TypeSignature.Parameter(label: "lhs", type: .javaObjectPointer), TypeSignature.Parameter(label: "rhs", type: .javaObjectPointer)], .bool, APIFlags(), nil)
var cdeclBody: [String]
let retString: String
if !classDeclaration.generics.isEmpty {
cdeclBody = [
"let lhs_ptr = SwiftObjectPointer.peer(of: lhs, options: \(options.jconvertibleOptions))",
"let lhs_swift: \(classDeclaration.signature.typeErasedClass) = lhs_ptr.pointee()!",
"let rhs_ptr = SwiftObjectPointer.peer(of: rhs, options: \(options.jconvertibleOptions))",
"let rhs_swift: \(classDeclaration.signature.typeErasedClass) = rhs_ptr.pointee()!"
]
retString = "return lhs_swift.islessthan(rhs_swift)"
} else {
cdeclBody = [
"let lhs_swift = \(classDeclaration.signature).fromJavaObject(lhs, options: \(options.jconvertibleOptions))",
"let rhs_swift = \(classDeclaration.signature).fromJavaObject(rhs, options: \(options.jconvertibleOptions))"
]
retString = "return lhs_swift < rhs_swift"
}
functionDeclaration.appendMainActorIsolated(&cdeclBody, in: classDeclaration, isReturn: true) { body, indentation in
body.append(indentation, retString)
}
let cdeclFunction = CDeclFunction(name: cdeclName, cdecl: cdecl, signature: cdeclType, body: cdeclBody)
cdeclFunctions.append(cdeclFunction)
}
@discardableResult private func update(_ interfaceDeclaration: KotlinInterfaceDeclaration) -> Bool {
guard !interfaceDeclaration.attributes.isNoBridge else {
return false
}
guard interfaceDeclaration.checkBridgable(direction: .toKotlin, options: options, translator: translator) else {
return false
}
guard let codebaseInfo = translator.codebaseInfo else {
return false
}
let extensions = codebaseInfo.typeInfos(forNamed: interfaceDeclaration.signature).filter { $0.declarationType == .extensionDeclaration }
interfaceDeclaration.extras = Self.bridgeExtras(interfaceDeclaration.extras)
interfaceDeclaration.inherits = interfaceDeclaration.inherits.compactMap {
if $0.isNamed("Comparable") {
return $0
} else if let bridgable = $0.checkBridgable(direction: .toKotlin, options: options, generics: interfaceDeclaration.generics, codebaseInfo: codebaseInfo) {
return bridgable.kotlinType
} else {
return nil
}
}
var extensionFunctionCount = 0
for member in interfaceDeclaration.members {
if let variableDeclaration = member as? KotlinVariableDeclaration {
let isExtension = extensions.contains { info in
info.variables.contains { $0.name == (variableDeclaration.preEscapedPropertyName ?? variableDeclaration.propertyName) }
}
if isExtension {
update(variableDeclaration, inExtensionOf: interfaceDeclaration)
} else {
if let bridgable = variableDeclaration.checkBridgable(direction: .toKotlin, options: options, translator: translator) {
updateDeclaration(variableDeclaration, with: bridgable)
KotlinBridgeToSwiftVisitor.appendCallbackFunction(for: variableDeclaration, bridgable: bridgable, modifiers: variableDeclaration.modifiers)
}
}
} else if let functionDeclaration = member as? KotlinFunctionDeclaration {
let isExtension = extensions.contains { info in
info.functions.contains { $0.name == (functionDeclaration.preEscapedName ?? functionDeclaration.name) && $0.signature == functionDeclaration.functionType }
}
if isExtension {
if update(functionDeclaration, inExtensionOf: interfaceDeclaration, uniquifier: extensionFunctionCount) {
extensionFunctionCount += 1
}
} else {
if let bridgable = functionDeclaration.checkBridgable(direction: .toKotlin, options: options, translator: translator) {
updateDeclaration(functionDeclaration, with: bridgable)
KotlinBridgeToSwiftVisitor.appendCallbackFunction(for: functionDeclaration, bridgable: bridgable, modifiers: functionDeclaration.modifiers)
}
}
}
}
// Must do this last after determining member generic constraints
interfaceDeclaration.generics = interfaceDeclaration.generics.compactMapBridgable(direction: .toKotlin, options: options, codebaseInfo: codebaseInfo)
return true
}
@discardableResult private func update(_ classDeclaration: KotlinClassDeclaration) -> Bool {
guard !classDeclaration.isGenerated else {
return false
}
guard !classDeclaration.attributes.isNoBridge else {
return false
}
guard classDeclaration.checkBridgable(direction: .toKotlin, options: options, translator: translator) else {
return false
}
guard let codebaseInfo = translator.codebaseInfo else {
return false
}
let superclassInfo = classDeclaration.superclassInfo(translator: translator)
if let superclassInfo {
guard !superclassInfo.attributes.isBridgeToSwift else {
classDeclaration.messages.append(.kotlinBridgeSuperclassBridging(classDeclaration, source: translator.syntaxTree.source))
return false
}
guard !superclassInfo.attributes.isBridgeToKotlin || (classDeclaration.generics.isEmpty && superclassInfo.generics.isEmpty) else {
classDeclaration.messages.append(.kotlinBridgeUnsupportedFeature(classDeclaration, feature: "inheritance of generic classes", source: translator.syntaxTree.source))
return false
}
}
// Figure out our subclass depth within the bridged hierarchy. -1 means not inheritable, 0 means base type
let subclassDepth: Int
if let superclassInfo, superclassInfo.attributes.isBridgeToKotlin {
let hierarchy = codebaseInfo.global.inheritanceChainSignatures(forNamed: superclassInfo.signature)
var depth = 1
for i in 1..<hierarchy.count {
if let typeInfo = codebaseInfo.primaryTypeInfo(forNamed: hierarchy[i]), typeInfo.attributes.isBridgeToKotlin {
depth += 1
} else {
break
}
}
subclassDepth = depth
} else if classDeclaration.declarationType == .classDeclaration && !classDeclaration.modifiers.isFinal {
subclassDepth = 0
} else {
subclassDepth = -1
}
let maximumDepth = 4
guard subclassDepth < maximumDepth else {
classDeclaration.messages.append(.kotlinBridgeToKotlinSubclassDepth(classDeclaration, maximumDepth: maximumDepth, source: translator.syntaxTree.source))
return false