forked from swiftlang/swift-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJNISwift2JavaGenerator+JavaBindingsPrinting.swift
More file actions
1006 lines (884 loc) · 33.9 KB
/
JNISwift2JavaGenerator+JavaBindingsPrinting.swift
File metadata and controls
1006 lines (884 loc) · 33.9 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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2025 Apple Inc. and the Swift.org project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Swift.org project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import CodePrinting
import Foundation
import OrderedCollections
import SwiftJavaConfigurationShared
import SwiftJavaJNICore
// MARK: Defaults
extension JNISwift2JavaGenerator {
/// Default set Java imports for every generated file
static let defaultJavaImports: [String] = [
"org.swift.swiftkit.core.*",
"org.swift.swiftkit.core.util.*",
"org.swift.swiftkit.core.collections.*",
"java.util.*",
"java.util.concurrent.atomic.AtomicBoolean",
// NonNull, Unsigned and friends
"org.swift.swiftkit.core.annotations.*",
]
}
// MARK: Printing
extension JNISwift2JavaGenerator {
func writeExportedJavaSources() throws {
var printer = CodePrinter()
try writeExportedJavaSources(&printer)
}
package func writeExportedJavaSources(_ printer: inout CodePrinter) throws {
let typesToExport: [(key: String, value: ImportedNominalType)]
if let singleType = config.singleType {
typesToExport = analysis.importedTypes
.filter { $0.key == singleType }
.sorted(by: { $0.key < $1.key })
} else {
typesToExport = analysis.importedTypes
.sorted(by: { $0.key < $1.key })
}
var exportedFileNames: OrderedSet<String> = []
// Each parent type goes into its own file
// any nested types are printed inside the body as `static class`
for (_, ty) in typesToExport.filter({ _, type in type.parent == nil }) {
let filename = "\(ty.effectiveJavaSimpleName).java"
logger.debug("Printing contents: \(filename)")
printImportedNominal(&printer, ty)
if let outputFile = try printer.writeContents(
outputDirectory: javaOutputDirectory,
javaPackagePath: javaPackagePath,
filename: filename,
) {
exportedFileNames.append(outputFile.path(percentEncoded: false))
logger.info("[swift-java] Generated: \(ty.effectiveJavaSimpleName.bold).java (at \(outputFile))")
}
}
// Skip the module-level .swift file when generating for a single type
if config.singleType == nil {
let filename = "\(self.swiftModuleName).java"
logger.trace("Printing module class: \(filename)")
printModule(&printer)
if let outputFile = try printer.writeContents(
outputDirectory: javaOutputDirectory,
javaPackagePath: javaPackagePath,
filename: filename,
) {
exportedFileNames.append(outputFile.path(percentEncoded: false))
logger.info("[swift-java] Generated: \(self.swiftModuleName).java (at \(outputFile))")
}
}
// Write java sources list file
if let generatedJavaSourcesListFileOutput = config.generatedJavaSourcesListFileOutput, !exportedFileNames.isEmpty {
let outputPath = URL(fileURLWithPath: javaOutputDirectory).appending(path: generatedJavaSourcesListFileOutput)
try exportedFileNames.joined(separator: "\n").write(
to: outputPath,
atomically: true,
encoding: .utf8,
)
logger.info("Generated file at \(outputPath)")
}
}
private func printModule(_ printer: inout CodePrinter) {
printHeader(&printer)
printPackage(&printer)
printImports(&printer)
self.currentJavaIdentifiers = JavaIdentifierFactory(
self.analysis.importedGlobalFuncs + self.analysis.importedGlobalVariables
)
printModuleClass(&printer) { printer in
printer.print(
"""
static final java.lang.String LIB_NAME = "\(config.nativeLibraryName ?? swiftModuleName)";
"""
)
if let overrideLoading = config.overrideStaticBlockLibraryLoading {
if !overrideLoading.isEmpty {
let body = overrideLoading.map { " \($0)" }.joined(separator: "\n")
printer.print(
"""
static {
\(body)
}
"""
)
}
} else {
printer.print(
"""
static {
SwiftLibraries.loadLibraryWithFallbacks(SwiftLibraries.LIB_NAME_SWIFT_JAVA);
SwiftLibraries.loadLibraryWithFallbacks(LIB_NAME);
}
"""
)
}
for decl in analysis.importedGlobalFuncs {
self.logger.trace("Print global function: \(decl)")
printFunctionDowncallMethods(&printer, decl)
printer.println()
}
for decl in analysis.importedGlobalVariables {
self.logger.trace("Print global variable: \(decl)")
printFunctionDowncallMethods(&printer, decl)
printer.println()
}
}
}
private func printImportedNominal(_ printer: inout CodePrinter, _ decl: ImportedNominalType) {
printHeader(&printer)
printPackage(&printer)
printImports(&printer)
self.currentJavaIdentifiers = JavaIdentifierFactory(
decl.initializers + decl.variables + decl.methods
)
switch decl.swiftNominal.kind {
case .actor, .class, .enum, .struct:
printConcreteType(&printer, decl)
case .protocol:
printProtocol(&printer, decl)
}
}
private func printProtocol(_ printer: inout CodePrinter, _ decl: ImportedNominalType) {
var extends = [String]()
// If we cannot generate Swift wrappers
// that allows the user to implement the wrapped interface in Java
// then we require only JExtracted types can conform to this.
if !self.interfaceProtocolWrappers.keys.contains(decl) {
extends.append("JNISwiftInstance")
}
let extendsString = extends.isEmpty ? "" : " extends \(extends.joined(separator: ", "))"
printer.printBraceBlock("public interface \(decl.effectiveJavaSimpleName)\(extendsString)") { printer in
for initializer in decl.initializers {
self.logger.debug("Skipping static method '\(initializer.name)'")
}
for method in decl.methods {
if method.isStatic {
self.logger.debug("Skipping static method '\(method.name)'")
continue
}
printFunctionDowncallMethods(&printer, method, skipMethodBody: true)
printer.println()
}
for variable in decl.variables {
if variable.isStatic {
self.logger.debug("Skipping static property '\(variable.name)'")
continue
}
printFunctionDowncallMethods(&printer, variable, skipMethodBody: true)
printer.println()
}
}
}
private func printConcreteType(_ printer: inout CodePrinter, _ decl: ImportedNominalType) {
let savedPrintingTypeName = self.currentPrintingTypeName
let savedPrintingType = self.currentPrintingType
self.currentPrintingTypeName = decl.effectiveJavaTypeName
self.currentPrintingType = decl
defer {
self.currentPrintingTypeName = savedPrintingTypeName
self.currentPrintingType = savedPrintingType
}
printNominal(&printer, decl) { printer in
printer.print(
"""
static final java.lang.String LIB_NAME = "\(config.nativeLibraryName ?? swiftModuleName)";
"""
)
if let overrideLoading = config.overrideStaticBlockLibraryLoading {
if !overrideLoading.isEmpty {
let body = overrideLoading.map { " \($0)" }.joined(separator: "\n")
printer.print(
"""
@SuppressWarnings("unused")
private static final boolean INITIALIZED_LIBS = initializeLibs();
static boolean initializeLibs() {
\(body)
return true;
}
"""
)
}
} else {
printer.print(
"""
@SuppressWarnings("unused")
private static final boolean INITIALIZED_LIBS = initializeLibs();
static boolean initializeLibs() {
SwiftLibraries.loadLibraryWithFallbacks(SwiftLibraries.LIB_NAME_SWIFT_JAVA);
SwiftLibraries.loadLibraryWithFallbacks(LIB_NAME);
return true;
}
"""
)
}
let nestedTypes = self.analysis.importedTypes.filter { _, type in
type.parent == decl.swiftNominal
}
for nestedType in nestedTypes {
printConcreteType(&printer, nestedType.value)
printer.println()
}
printer.print(
"""
/**
* The designated constructor of any imported Swift types.
*
* @param selfPointer a pointer to the memory containing the value
* @param swiftArena the arena this object belongs to. When the arena goes out of scope, this value is destroyed.
*/
"""
)
// Specialized types are concrete — no selfTypePointer needed
let isEffectivelyGeneric = decl.swiftNominal.isGeneric && !decl.isSpecialization
var swiftPointerParams = ["selfPointer"]
if isEffectivelyGeneric {
swiftPointerParams.append("selfTypePointer")
}
let swiftPointerArg = swiftPointerParams.map { "long \($0)" }.joined(separator: ", ")
printer.printBraceBlock("private \(decl.effectiveJavaSimpleName)(\(swiftPointerArg), SwiftArena swiftArena)") { printer in
for param in swiftPointerParams {
printer.print(
"""
SwiftObjects.requireNonZero(\(param), "\(param)");
this.\(param) = \(param);
"""
)
}
printer.print(
"""
// Only register once we have fully initialized the object since this will need the object pointer.
swiftArena.register(this);
"""
)
}
printer.println()
let genericClause = decl.javaGenericClause
let javaName = decl.effectiveJavaSimpleName
printer.print(
"""
/**
* Assume that the passed {@code long} represents a memory address of a {@link \(javaName)}.
* <p>
* Warnings:
* <ul>
* <li>No checks are performed about the compatibility of the pointed at memory and the actual \(javaName) types.</li>
* <li>This operation does not copy, or retain, the pointed at pointer, so its lifetime must be ensured manually to be valid when wrapping.</li>
* </ul>
*/
public static\(genericClause) \(javaName)\(genericClause) wrapMemoryAddressUnsafe(\(swiftPointerArg), SwiftArena swiftArena) {
return new \(javaName)\(genericClause)(\(swiftPointerParams.joined(separator: ", ")), swiftArena);
}
public static\(genericClause) \(javaName)\(genericClause) wrapMemoryAddressUnsafe(\(swiftPointerArg)) {
return new \(javaName)\(genericClause)(\(swiftPointerParams.joined(separator: ", ")), SwiftMemoryManagement.DEFAULT_SWIFT_JAVA_AUTO_ARENA);
}
"""
)
printer.print(
"""
/** Pointer to the "self". */
private final long selfPointer;
/** Used to track additional state of the underlying object, e.g. if it was explicitly destroyed. */
private final AtomicBoolean $state$destroyed = new AtomicBoolean(false);
public long $memoryAddress() {
return this.selfPointer;
}
@Override
public AtomicBoolean $statusDestroyedFlag() {
return $state$destroyed;
}
"""
)
if isEffectivelyGeneric {
printer.print("/** Pointer to the metatype of Self */")
printer.print("private final long selfTypePointer;")
}
printer.println()
if decl.swiftNominal.kind == .enum {
printEnumHelpers(&printer, decl)
printer.println()
}
for initializer in decl.initializers {
printFunctionDowncallMethods(&printer, initializer)
printer.println()
}
for method in decl.methods {
printFunctionDowncallMethods(&printer, method)
printer.println()
}
for variable in decl.variables {
printFunctionDowncallMethods(&printer, variable)
printer.println()
}
printSpecificTypeHelpers(&printer, decl)
printTypeMetadataAddressFunction(&printer, decl)
printer.println()
printer.print(
"""
public java.lang.String toString() {
return SwiftObjects.toString(this.$memoryAddress(), this.$typeMetadataAddress());
}
public java.lang.String toDebugString() {
return SwiftObjects.toDebugString(this.$memoryAddress(), this.$typeMetadataAddress());
}
"""
)
printer.println()
printDestroyFunction(&printer, decl)
}
}
/// Prints helpers for specific types like `Foundation.Date`
private func printSpecificTypeHelpers(_ printer: inout CodePrinter, _ decl: ImportedNominalType) {
guard let knownType = decl.swiftNominal.knownTypeKind else { return }
switch knownType {
case .foundationDate, .essentialsDate:
printFoundationDateHelpers(&printer, decl)
case .foundationData, .essentialsData:
printFoundationDataHelpers(&printer, decl)
default:
break
}
}
private func printHeader(_ printer: inout CodePrinter) {
printer.print(
"""
// Generated by jextract-swift
// Swift module: \(swiftModuleName)
"""
)
}
private func printPackage(_ printer: inout CodePrinter) {
printer.print(
"""
package \(javaPackage);
"""
)
}
private func printImports(_ printer: inout CodePrinter) {
for i in JNISwift2JavaGenerator.defaultJavaImports {
printer.print("import \(i);")
}
printer.print("")
}
private func printNominal(
_ printer: inout CodePrinter,
_ decl: ImportedNominalType,
body: (inout CodePrinter) -> Void,
) {
if decl.swiftNominal.isSendable {
printer.print("@ThreadSafe // Sendable")
}
var modifiers = ["public"]
if decl.parent != nil {
modifiers.append("static")
}
modifiers.append("final")
var implements = ["JNISwiftInstance"]
implements += decl.inheritedTypes
.compactMap(\.asNominalTypeDeclaration)
.filter { $0.kind == .protocol }
.map(\.name)
let implementsClause = implements.joined(separator: ", ")
// Specialized types are concrete — no generic clause on the Java side
let genericClause = decl.javaGenericClause
printer.printBraceBlock(
"\(modifiers.joined(separator: " ")) class \(decl.effectiveJavaSimpleName)\(genericClause) implements \(implementsClause)"
) { printer in
body(&printer)
}
}
private func printModuleClass(_ printer: inout CodePrinter, body: (inout CodePrinter) -> Void) {
printer.printBraceBlock("public final class \(swiftModuleName)") { printer in
body(&printer)
}
}
private func printEnumHelpers(_ printer: inout CodePrinter, _ decl: ImportedNominalType) {
printEnumDiscriminator(&printer, decl)
printer.println()
printEnumCaseInterface(&printer, decl)
printer.println()
printEnumStaticInitializers(&printer, decl)
printer.println()
printEnumCases(&printer, decl)
}
private func printEnumDiscriminator(_ printer: inout CodePrinter, _ decl: ImportedNominalType) {
if decl.cases.isEmpty {
return
}
printer.printBraceBlock("public enum Discriminator") { printer in
printer.print(
decl.cases.map { $0.name.uppercased() }.joined(separator: ",\n")
)
}
printer.printBraceBlock("public Discriminator getDiscriminator()") { printer in
printer.print("var raw = SwiftObjects.getRawDiscriminator(this.$memoryAddress(), this.$typeMetadataAddress());")
printer.print("return Discriminator.values()[raw];")
}
}
private func printEnumCaseInterface(_ printer: inout CodePrinter, _ decl: ImportedNominalType) {
if decl.cases.isEmpty {
return
}
printer.printBraceBlock("public sealed interface Case") { printer in
for enumCase in decl.cases {
guard let translatedCase = self.translatedEnumCase(for: enumCase) else {
continue
}
let members = translatedCase.translatedValues.map {
$0.parameter.renderParameter()
}
let caseName = enumCase.name.firstCharacterUppercased
// Print record
printer.printBraceBlock("record \(caseName)(\(members.joined(separator: ", "))) implements Case") {
printer in
let nativeParameters = zip(translatedCase.translatedValues, translatedCase.parameterConversions).map {
value,
conversion in
"\(conversion.native.javaType) \(value.parameter.name)"
}
printer.print("record _NativeParameters(\(nativeParameters.joined(separator: ", "))) {}")
}
}
}
printer.println()
let requiresSwiftArena = decl.cases.compactMap {
self.translatedEnumCase(for: $0)
}.contains(where: \.requiresSwiftArena)
printer.printBraceBlock("public Case getCase(\(requiresSwiftArena ? "SwiftArena swiftArena" : ""))") { printer in
printer.printBraceBlock("return switch (this.getDiscriminator())", .semicolonNewLine) { printer in
for enumCase in decl.cases {
guard let translatedCase = self.translatedEnumCase(for: enumCase) else {
continue
}
let arenaArgument = translatedCase.requiresSwiftArena ? "swiftArena" : ""
printer.print(
"case \(enumCase.name.uppercased()) -> this.getAs\(enumCase.name.firstCharacterUppercased)(\(arenaArgument)).orElseThrow();"
)
}
}
}
}
private func printEnumStaticInitializers(_ printer: inout CodePrinter, _ decl: ImportedNominalType) {
let isEffectivelyGeneric = decl.swiftNominal.isGeneric && !decl.isSpecialization
if !decl.cases.isEmpty && isEffectivelyGeneric {
self.logger.debug("Skipping generic static initializers in '\(decl.effectiveJavaSimpleName)'")
return
}
for enumCase in decl.cases {
printFunctionDowncallMethods(&printer, enumCase.caseFunction)
}
}
private func printEnumCases(_ printer: inout CodePrinter, _ decl: ImportedNominalType) {
for enumCase in decl.cases {
guard let translatedCase = self.translatedEnumCase(for: enumCase) else {
return
}
self.printJavaBindingWrapperMethod(&printer, translatedCase.getAsCaseFunction, skipMethodBody: false)
printer.println()
}
}
private func printFunctionDowncallMethods(
_ printer: inout CodePrinter,
_ decl: ImportedFunc,
skipMethodBody: Bool = false,
) {
guard translatedDecl(for: decl) != nil else {
// Failed to translate. Skip.
return
}
printer.printSeparator(decl.displayName)
printJavaBindingWrapperHelperClass(&printer, decl)
printJavaBindingWrapperMethod(&printer, decl, skipMethodBody: skipMethodBody)
// Print any additional types we may need to emit, e.g. named tuples are emitted as static classes
// right next to the func that is using them.
printNecessarySupportTypes(&printer, decl)
}
/// Print the helper type container for a user-facing Java API.
///
/// * User-facing functional interfaces.
private func printJavaBindingWrapperHelperClass(
_ printer: inout CodePrinter,
_ decl: ImportedFunc,
) {
let translated = self.translatedDecl(for: decl)!
if translated.functionTypes.isEmpty {
return
}
printer.printBraceBlock(
"""
public static class \(translated.name)
"""
) { printer in
for functionType in translated.functionTypes {
printJavaBindingWrapperFunctionTypeHelper(&printer, functionType)
}
}
}
/// Print "wrapper" functional interface representing a Swift closure type.
func printJavaBindingWrapperFunctionTypeHelper(
_ printer: inout CodePrinter,
_ functionType: TranslatedFunctionType,
) {
let apiParams = functionType.parameters.map({ $0.parameter.renderParameter() })
printer.print(
"""
@FunctionalInterface
public interface \(functionType.name) {
\(functionType.result.javaType) apply(\(apiParams.joined(separator: ", ")));
}
"""
)
}
private func printNecessarySupportTypes(
_ printer: inout CodePrinter,
_ decl: ImportedFunc
) {
let translatedDecl = translatedDecl(for: decl)!
for labeledTuple in translatedDecl.usedLabeledTuples {
printAdHocLabeledTupleStaticClass(&printer, labeledTuple)
}
}
private func printJavaBindingWrapperMethod(
_ printer: inout CodePrinter,
_ decl: ImportedFunc,
skipMethodBody: Bool,
) {
guard let translatedDecl = translatedDecl(for: decl) else {
fatalError("Decl was not translated, \(decl)")
}
printJavaBindingWrapperMethod(&printer, translatedDecl, importedFunc: decl, skipMethodBody: skipMethodBody)
}
private func printJavaBindingWrapperMethod(
_ printer: inout CodePrinter,
_ translatedDecl: TranslatedFunctionDecl,
importedFunc: ImportedFunc? = nil,
skipMethodBody: Bool,
) {
var modifiers = ["public"]
if translatedDecl.isStatic {
modifiers.append("static")
}
let translatedSignature = translatedDecl.translatedFunctionSignature
let resultType = translatedSignature.result.javaType
var parameters = translatedDecl.translatedFunctionSignature.parameters.map { $0.parameter.renderParameter() }
let throwsClause = translatedDecl.throwsClause()
let generics = translatedDecl.translatedFunctionSignature.parameters.reduce(into: [(String, [JavaType])]()) {
generics,
parameter in
guard case .generic(let name, let extends) = parameter.parameter.type else {
return
}
generics.append((name, extends))
}
.map { "\($0) extends \($1.compactMap(\.className).joined(separator: " & "))" }
.joined(separator: ", ")
if !generics.isEmpty {
modifiers.append("<" + generics + ">")
}
var annotationsStr = translatedSignature.annotations.map({ $0.render() }).joined(separator: "\n")
if !annotationsStr.isEmpty { annotationsStr += "\n" }
let parametersStr = parameters.joined(separator: ", ")
// Print default global arena variation
// If we have enabled javaCallbacks we must emit default
// arena methods for protocols, as this is what
// Swift will call into, when you call a interface from Swift.
let shouldGenerateGlobalArenaVariation =
config.effectiveMemoryManagementMode.requiresGlobalArena && translatedSignature.requiresSwiftArena
let isParentProtocol = importedFunc?.parentType?.asNominalType?.isProtocol ?? false
if shouldGenerateGlobalArenaVariation {
if let importedFunc {
TranslatedDocumentation.printDocumentation(
importedFunc: importedFunc,
translatedDecl: translatedDecl,
config: config,
in: &printer,
)
}
var modifiers = modifiers
// If we are a protocol, we emit this as default method
if isParentProtocol {
modifiers.insert("default", at: 1)
}
printer.printBraceBlock(
"\(annotationsStr)\(modifiers.joined(separator: " ")) \(resultType) \(translatedDecl.name)(\(parametersStr))\(throwsClause)"
) { printer in
let globalArenaName = "SwiftMemoryManagement.DEFAULT_SWIFT_JAVA_AUTO_ARENA"
let arguments = translatedDecl.translatedFunctionSignature.parameters.map(\.parameter.name) + [globalArenaName]
let call = "\(translatedDecl.name)(\(arguments.joined(separator: ", ")))"
if translatedDecl.translatedFunctionSignature.result.javaType.isVoid {
printer.print("\(call);")
} else {
printer.print("return \(call);")
}
}
printer.println()
}
if translatedSignature.requiresSwiftArena {
parameters.append("SwiftArena swiftArena")
}
if let importedFunc {
TranslatedDocumentation.printDocumentation(
importedFunc: importedFunc,
translatedDecl: translatedDecl,
config: config,
in: &printer,
)
}
let signature =
"\(annotationsStr)\(modifiers.joined(separator: " ")) \(resultType) \(translatedDecl.name)(\(parameters.joined(separator: ", ")))\(throwsClause)"
if skipMethodBody {
printer.print("\(signature);")
} else {
printer.printBraceBlock(signature) { printer in
printDowncall(&printer, translatedDecl)
}
printNativeFunction(&printer, translatedDecl)
}
}
private func printNativeFunction(_ printer: inout CodePrinter, _ translatedDecl: TranslatedFunctionDecl) {
let nativeSignature = translatedDecl.nativeFunctionSignature
let resultType = nativeSignature.result.javaType
var parameters = nativeSignature.parameters.flatMap(\.parameters)
if let selfParameter = nativeSignature.selfParameter?.parameters {
parameters += selfParameter
}
if let selfTypeParameter = nativeSignature.selfTypeParameter?.parameters {
parameters += selfTypeParameter
}
parameters += nativeSignature.result.outParameters
let renderedParameters = parameters.map { javaParameter in
"\(javaParameter.type) \(javaParameter.name)"
}.joined(separator: ", ")
printer.print("private static native \(resultType) \(translatedDecl.nativeFunctionName)(\(renderedParameters));")
}
private func printDowncall(
_ printer: inout CodePrinter,
_ translatedDecl: TranslatedFunctionDecl,
) {
let translatedFunctionSignature = translatedDecl.translatedFunctionSignature
// Regular parameters.
var arguments = [String]()
for parameter in translatedFunctionSignature.parameters {
let lowered = parameter.conversion.render(&printer, parameter.parameter.name)
arguments.append(lowered)
}
// 'self' parameter.
if let selfParameter = translatedFunctionSignature.selfParameter {
let lowered = selfParameter.conversion.render(&printer, "this")
arguments.append(lowered)
}
// 'Self' metatype.
if let selfTypeParameter = translatedFunctionSignature.selfTypeParameter {
let lowered = selfTypeParameter.conversion.render(&printer, "this")
arguments.append(lowered)
}
// Indirect return receivers
for outParameter in translatedFunctionSignature.result.outParameters {
printer.print(
"\(outParameter.type) \(outParameter.name) = \(outParameter.allocation.render(type: outParameter.type));"
)
arguments.append(outParameter.name)
}
//=== Part 3: Downcall.
// TODO: If we always generate a native method and a "public" method, we can actually choose our own thunk names
// using the registry?
let effectiveParentName = self.currentPrintingTypeName ?? translatedDecl.parentName
let downcall =
"\(effectiveParentName.fullName).\(translatedDecl.nativeFunctionName)(\(arguments.joined(separator: ", ")))"
//=== Part 4: Convert the return value.
if translatedFunctionSignature.result.javaType.isVoid {
printer.print("\(downcall);")
} else {
let result: String
if translatedDecl.nativeFunctionSignature.result.javaType.isVoid {
printer.print("\(downcall);")
result = translatedFunctionSignature.result.conversion.render(&printer, "")
} else {
result = translatedFunctionSignature.result.conversion.render(&printer, downcall)
}
printer.print("return \(result);")
}
}
private func printTypeMetadataAddressFunction(_ printer: inout CodePrinter, _ type: ImportedNominalType) {
let isEffectivelyGeneric = type.swiftNominal.isGeneric && !type.isSpecialization
if isEffectivelyGeneric {
printer.print("@Override")
printer.printBraceBlock("public long $typeMetadataAddress()") { printer in
printer.print("return this.selfTypePointer;")
}
} else {
printer.print("private static native long $typeMetadataAddressDowncall();")
printer.print("@Override")
printer.printBraceBlock("public long $typeMetadataAddress()") { printer in
// INFO: We are omitting `CallTraces.traceDowncall` here.
// It internally calls `toString`, which in turn calls `$typeMetadataAddress`, creating an infinite loop.
printer.print("return \(type.effectiveJavaSimpleName).$typeMetadataAddressDowncall();")
}
}
}
/// Prints the destroy function for a `JNISwiftInstance`
private func printDestroyFunction(_ printer: inout CodePrinter, _ type: ImportedNominalType) {
let funcName = "$createDestroyFunction"
let isEffectivelyGeneric = type.swiftNominal.isGeneric && !type.isSpecialization
let typeName = type.effectiveJavaSimpleName
printer.print("@Override")
printer.printBraceBlock("public Runnable \(funcName)()") { printer in
printer.print("long self$ = this.$memoryAddress();")
printer.print("long selfType$ = this.$typeMetadataAddress();")
if isEffectivelyGeneric {
printer.print(
"""
if (CallTraces.TRACE_DOWNCALLS) {
CallTraces.traceDowncall("\(typeName).\(funcName)",
"this", this,
"self", self$,
"selfType", selfType$);
}
return new Runnable() {
@Override
public void run() {
if (CallTraces.TRACE_DOWNCALLS) {
CallTraces.traceDowncall("\(typeName).$destroy", "self", self$, "selfType", selfType$);
}
SwiftObjects.destroy(self$, selfType$);
}
};
"""
)
} else {
printer.print(
"""
if (CallTraces.TRACE_DOWNCALLS) {
CallTraces.traceDowncall("\(typeName).\(funcName)",
"this", this,
"self", self$);
}
return new Runnable() {
@Override
public void run() {
if (CallTraces.TRACE_DOWNCALLS) {
CallTraces.traceDowncall("\(typeName).$destroy", "self", self$);
}
SwiftObjects.destroy(self$, selfType$);
}
};
"""
)
}
}
}
private func printFoundationDateHelpers(_ printer: inout CodePrinter, _ decl: ImportedNominalType) {
printer.print(
"""
/**
* Converts this wrapped date to a Java {@link java.time.Instant}.
* <p>
* This method constructs the {@code Instant} using the underlying {@code double} value
* representing seconds since the Unix Epoch (January 1, 1970).
* </p>
*
* @return A {@code java.time.Instant} derived from the floating-point timestamp.
*/
public java.time.Instant toInstant() {
long seconds = (long) this.getTimeIntervalSince1970();
long nanos = Math.round((this.getTimeIntervalSince1970() - seconds) * 1_000_000_000);
return java.time.Instant.ofEpochSecond(seconds, nanos);
}
"""
)
printer.println()
printer.print(
"""
/**
* Initializes a Swift {@code Foundation.Date} from a Java {@link java.time.Instant}.
*
* <h3>Warning: Precision Loss</h3>
* <p>
* <strong>The input precision will be degraded.</strong>
* </p>
* <p>
* Java's {@code Instant} stores time with <strong>nanosecond</strong> precision (9 decimal places).
* However, this class stores time as a 64-bit floating-point value.
* </p>
* <p>
* This leaves enough capacity for <strong>microsecond</strong> precision (approx. 6 decimal places).
* </p>
* <p>
* Consequently, the last ~3 digits of the {@code Instant}'s nanosecond field will be
* truncated or subjected to rounding errors during conversion.
* </p>
*
* @param instant The source timestamp to convert.
* @return A date derived from the input instant with microsecond precision.
*/
public static Date fromInstant(java.time.Instant instant, SwiftArena swiftArena) {
Objects.requireNonNull(instant, "Instant cannot be null");
double timeIntervalSince1970 = instant.getEpochSecond() + (instant.getNano() / 1_000_000_000.0);
return Date.init(timeIntervalSince1970, swiftArena);
}
"""
)
}
private func printFoundationDataHelpers(_ printer: inout CodePrinter, _ decl: ImportedNominalType) {
printer.print(
"""
/**
* Creates a new Swift @{link Data} instance from a byte array.
*
* @param bytes The byte array to copy into the Data
* @param swiftArena The arena for memory management
* @return A new Data instance containing a copy of the bytes
*/
public static Data fromByteArray(byte[] bytes, SwiftArena swiftArena) {
Objects.requireNonNull(bytes, "bytes cannot be null");
return Data.init(bytes, swiftArena);
}
"""
)
printer.print(
"""
/**
* Copies the contents of this Data to a new byte array.
*
* This is a relatively efficient implementation, which avoids native array copies,
* however it will still perform a copy of the data onto the JVM heap, so use this
* only when necessary.
*
* </p> When utmost performance is necessary, you may want to investigate the FFM mode
* of jextract which is able to map memory more efficiently.
*
* @return A byte array containing a copy of this Data's bytes
*/
public byte[] toByteArray() {
return $toByteArray(this.$memoryAddress());
}
"""
)
printer.print(
"""
private static native byte[] $toByteArray(long selfPointer);
/**
* Copies the contents of this Data to a new byte array.
*
* @deprecated Prefer using the `toByteArray` method as it is more performant.
* This implementation uses a naive conversion path from native bytes into jbytes
* and then copying them onto the jvm heap.
*
* @return A byte array containing a copy of this Data's bytes
*/
@Deprecated(forRemoval = true)
public byte[] toByteArrayIndirectCopy() {
return $toByteArrayIndirectCopy(this.$memoryAddress());
}