forked from swiftlang/swift-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSwift2JavaTranslator+Printing.swift
More file actions
1015 lines (870 loc) · 32 KB
/
Swift2JavaTranslator+Printing.swift
File metadata and controls
1015 lines (870 loc) · 32 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) 2024 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 Foundation
import SwiftBasicFormat
import SwiftParser
import SwiftSyntax
// ==== ---------------------------------------------------------------------------------------------------------------
// MARK: File writing
let PATH_SEPARATOR = "/" // TODO: Windows
extension Swift2JavaTranslator {
/// Every imported public type becomes a public class in its own file in Java.
public func writeExportedJavaSources(outputDirectory: String) throws {
var printer = CodePrinter()
try writeExportedJavaSources(outputDirectory: outputDirectory, printer: &printer)
}
public func writeExportedJavaSources(outputDirectory: String, printer: inout CodePrinter) throws {
for (_, ty) in importedTypes.sorted(by: { (lhs, rhs) in lhs.key < rhs.key }) {
let filename = "\(ty.javaClassName).java"
log.info("Printing contents: \(filename)")
printImportedClass(&printer, ty)
if let outputFile = try printer.writeContents(
outputDirectory: outputDirectory,
javaPackagePath: javaPackagePath,
filename: filename
) {
print("[swift-java] Generated: \(ty.javaClassName.bold).java (at \(outputFile))")
}
}
do {
let filename = "\(self.swiftModuleName).java"
log.info("Printing contents: \(filename)")
printModule(&printer)
if let outputFile = try printer.writeContents(
outputDirectory: outputDirectory,
javaPackagePath: javaPackagePath,
filename: filename)
{
print("[swift-java] Generated: \(self.swiftModuleName).java (at \(outputFile)")
}
}
}
public func writeSwiftThunkSources(outputDirectory: String) throws {
var printer = CodePrinter()
try writeSwiftThunkSources(outputDirectory: outputDirectory, printer: &printer)
}
public func writeSwiftThunkSources(outputDirectory: String, printer: inout CodePrinter) throws {
let moduleFilenameBase = "\(self.swiftModuleName)Module+SwiftJava"
let moduleFilename = "\(moduleFilenameBase).swift"
do {
log.info("Printing contents: \(moduleFilename)")
try printGlobalSwiftThunkSources(&printer)
if let outputFile = try printer.writeContents(
outputDirectory: outputDirectory,
javaPackagePath: nil,
filename: moduleFilename)
{
print("[swift-java] Generated: \(moduleFilenameBase.bold).swift (at \(outputFile)")
}
} catch {
log.warning("Failed to write to Swift thunks: \(moduleFilename)")
}
// === All types
for (_, ty) in importedTypes.sorted(by: { (lhs, rhs) in lhs.key < rhs.key }) {
let fileNameBase = "\(ty.swiftNominal.qualifiedName)+SwiftJava"
let filename = "\(fileNameBase).swift"
log.info("Printing contents: \(filename)")
do {
try printSwiftThunkSources(&printer, ty: ty)
if let outputFile = try printer.writeContents(
outputDirectory: outputDirectory,
javaPackagePath: nil,
filename: filename)
{
print("[swift-java] Generated: \(fileNameBase.bold).swift (at \(outputFile)")
}
} catch {
log.warning("Failed to write to Swift thunks: \(filename)")
}
}
}
public func printGlobalSwiftThunkSources(_ printer: inout CodePrinter) throws {
let stt = SwiftThunkTranslator(self)
printer.print(
"""
// Generated by swift-java
import SwiftKitSwift
""")
for thunk in stt.renderGlobalThunks() {
printer.print(thunk)
printer.println()
}
}
public func printSwiftThunkSources(_ printer: inout CodePrinter, decl: ImportedFunc) {
let stt = SwiftThunkTranslator(self)
for thunk in stt.render(forFunc: decl) {
printer.print(thunk)
printer.println()
}
}
package func printSwiftThunkSources(_ printer: inout CodePrinter, ty: ImportedNominalType) throws {
let stt = SwiftThunkTranslator(self)
printer.print(
"""
// Generated by swift-java
import SwiftKitSwift
"""
)
for thunk in stt.renderThunks(forType: ty) {
printer.print("\(thunk)")
printer.print("")
}
}
/// A module contains all static and global functions from the Swift module,
/// potentially from across multiple swift interfaces.
public func writeExportedJavaModule(outputDirectory: String) throws {
var printer = CodePrinter()
try writeExportedJavaModule(outputDirectory: outputDirectory, printer: &printer)
}
public func writeExportedJavaModule(outputDirectory: String, printer: inout CodePrinter) throws {
printModule(&printer)
if let file = try printer.writeContents(
outputDirectory: outputDirectory,
javaPackagePath: javaPackagePath,
filename: "\(swiftModuleName).java"
) {
self.log.info("Generated: \(file): \("done".green).")
}
}
}
// ==== ---------------------------------------------------------------------------------------------------------------
// MARK: Java/text printing
extension Swift2JavaTranslator {
/// Render the Java file contents for an imported Swift module.
///
/// This includes any Swift global functions in that module, and some general type information and helpers.
public func printModule(_ printer: inout CodePrinter) {
printHeader(&printer)
printPackage(&printer)
printImports(&printer)
printModuleClass(&printer) { printer in
// TODO: print all "static" methods
for decl in importedGlobalFuncs {
self.log.trace("Print imported decl: \(decl)")
printFunctionDowncallMethods(&printer, decl)
}
}
}
package func printImportedClass(_ printer: inout CodePrinter, _ decl: ImportedNominalType) {
printHeader(&printer)
printPackage(&printer)
printImports(&printer)
printNominal(&printer, decl) { printer in
// Prepare type metadata, we're going to need these when invoking e.g. initializers so cache them in a static.
// We call into source swift-java source generated accessors which give us the type of the Swift object:
// TODO: seems we no longer need the mangled name per se, so avoiding such constant and downcall
// printer.printParts(
// "public static final String TYPE_MANGLED_NAME = ",
// SwiftKitPrinting.renderCallGetSwiftTypeMangledName(module: self.swiftModuleName, nominal: decl),
// ";"
// )
// We use a static field to abuse the initialization order such that by the time we get type metadata,
// we already have loaded the library where it will be obtained from.
printer.printParts(
"""
@SuppressWarnings("unused")
private static final boolean INITIALIZED_LIBS = initializeLibs();
static boolean initializeLibs() {
System.loadLibrary(SwiftKit.STDLIB_DYLIB_NAME);
System.loadLibrary("SwiftKitSwift");
System.loadLibrary(LIB_NAME);
return true;
}
public static final SwiftAnyType TYPE_METADATA =
new SwiftAnyType(\(SwiftKitPrinting.renderCallGetSwiftType(module: self.swiftModuleName, nominal: decl)));
public final SwiftAnyType $swiftType() {
return TYPE_METADATA;
}
"""
)
printer.print("")
// Layout of the class
printClassMemoryLayout(&printer, decl)
printer.print("")
// Initializers
for initDecl in decl.initializers {
printClassConstructors(&printer, initDecl)
}
// Properties
for varDecl in decl.variables {
printVariableDowncallMethods(&printer, varDecl)
}
// Methods
for funcDecl in decl.methods {
printFunctionDowncallMethods(&printer, funcDecl)
}
// Helper methods and default implementations
printHeapObjectToStringMethod(&printer, decl)
}
}
public func printHeader(_ printer: inout CodePrinter) {
printer.print(
"""
// Generated by jextract-swift
// Swift module: \(swiftModuleName)
"""
)
}
public func printPackage(_ printer: inout CodePrinter) {
printer.print(
"""
package \(javaPackage);
"""
)
}
public func printImports(_ printer: inout CodePrinter) {
for i in Swift2JavaTranslator.defaultJavaImports {
printer.print("import \(i);")
}
printer.print("")
}
package func printNominal(
_ printer: inout CodePrinter, _ decl: ImportedNominalType, body: (inout CodePrinter) -> Void
) {
let parentProtocol: String
if decl.isReferenceType {
parentProtocol = "SwiftHeapObject"
} else {
parentProtocol = "SwiftValue"
}
printer.printTypeDecl("public final class \(decl.javaClassName) extends SwiftInstance implements \(parentProtocol)") {
printer in
// Constants
printClassConstants(printer: &printer)
body(&printer)
}
}
public func printModuleClass(_ printer: inout CodePrinter, body: (inout CodePrinter) -> Void) {
printer.printTypeDecl("public final class \(swiftModuleName)") { printer in
printPrivateConstructor(&printer, swiftModuleName)
// Constants
printClassConstants(printer: &printer)
printer.print(
"""
static MemorySegment findOrThrow(String symbol) {
return SYMBOL_LOOKUP.find(symbol)
.orElseThrow(() -> new UnsatisfiedLinkError("unresolved symbol: %s".formatted(symbol)));
}
"""
)
printer.print(
"""
static MethodHandle upcallHandle(Class<?> fi, String name, FunctionDescriptor fdesc) {
try {
return MethodHandles.lookup().findVirtual(fi, name, fdesc.toMethodType());
} catch (ReflectiveOperationException ex) {
throw new AssertionError(ex);
}
}
"""
)
printer.print(
"""
static MemoryLayout align(MemoryLayout layout, long align) {
return switch (layout) {
case PaddingLayout p -> p;
case ValueLayout v -> v.withByteAlignment(align);
case GroupLayout g -> {
MemoryLayout[] alignedMembers = g.memberLayouts().stream()
.map(m -> align(m, align)).toArray(MemoryLayout[]::new);
yield g instanceof StructLayout ?
MemoryLayout.structLayout(alignedMembers) : MemoryLayout.unionLayout(alignedMembers);
}
case SequenceLayout s -> MemoryLayout.sequenceLayout(s.elementCount(), align(s.elementLayout(), align));
};
}
"""
)
// SymbolLookup.libraryLookup is platform dependent and does not take into account java.library.path
// https://bugs.openjdk.org/browse/JDK-8311090
printer.print(
"""
static final SymbolLookup SYMBOL_LOOKUP = getSymbolLookup();
private static SymbolLookup getSymbolLookup() {
// Ensure Swift and our Lib are loaded during static initialization of the class.
SwiftKit.loadLibrary("swiftCore");
SwiftKit.loadLibrary("SwiftKitSwift");
SwiftKit.loadLibrary(LIB_NAME);
if (PlatformUtils.isMacOS()) {
return SymbolLookup.libraryLookup(System.mapLibraryName(LIB_NAME), LIBRARY_ARENA)
.or(SymbolLookup.loaderLookup())
.or(Linker.nativeLinker().defaultLookup());
} else {
return SymbolLookup.loaderLookup()
.or(Linker.nativeLinker().defaultLookup());
}
}
"""
)
body(&printer)
}
}
private func printClassConstants(printer: inout CodePrinter) {
printer.print(
"""
static final String LIB_NAME = "\(swiftModuleName)";
static final Arena LIBRARY_ARENA = Arena.ofAuto();
"""
)
}
private func printPrivateConstructor(_ printer: inout CodePrinter, _ typeName: String) {
printer.print(
"""
private \(typeName)() {
// Should not be called directly
}
// Static enum to force initialization
private static enum Initializer {
FORCE; // Refer to this to force outer Class initialization (and static{} blocks to trigger)
}
"""
)
}
private func printClassMemoryLayout(_ printer: inout CodePrinter, _ decl: ImportedNominalType) {
printer.print(
"""
private static final GroupLayout $LAYOUT = (GroupLayout) SwiftValueWitnessTable.layoutOfSwiftType(TYPE_METADATA.$memorySegment());
public final GroupLayout $layout() {
return $LAYOUT;
}
"""
)
}
public func printClassConstructors(_ printer: inout CodePrinter, _ decl: ImportedFunc) {
guard let parentName = decl.parent else {
fatalError("init must be inside a parent type! Was: \(decl)")
}
printer.printSeparator(decl.identifier)
let descClassIdentifier = renderDescClassName(decl)
printer.printTypeDecl("private static class \(descClassIdentifier)") { printer in
printFunctionDescriptorValue(&printer, decl)
printAccessorFunctionAddr(&printer, decl)
printMethodDowncallHandleForAddrDesc(&printer)
}
printNominalInitializerConstructors(&printer, decl, parentName: parentName)
}
public func printNominalInitializerConstructors(
_ printer: inout CodePrinter,
_ decl: ImportedFunc,
parentName: TranslatedType
) {
let descClassIdentifier = renderDescClassName(decl)
printer.print(
"""
/**
* Create an instance of {@code \(parentName.unqualifiedJavaTypeName)}.
*
\(decl.renderCommentSnippet ?? " *")
*/
public \(parentName.unqualifiedJavaTypeName)(\(renderJavaParamDecls(decl, paramPassingStyle: .wrapper))) {
this(SwiftArena.ofAuto(), \(renderForwardJavaParams(decl, paramPassingStyle: .wrapper)));
}
"""
)
printer.print(
"""
/**
* Create an instance of {@code \(parentName.unqualifiedJavaTypeName)}.
* This instance is managed by the passed in {@link SwiftArena} and may not outlive the arena's lifetime.
*
\(decl.renderCommentSnippet ?? " *")
*/
public \(parentName.unqualifiedJavaTypeName)(SwiftArena arena, \(renderJavaParamDecls(decl, paramPassingStyle: .wrapper))) {
super(() -> {
var mh$ = \(descClassIdentifier).HANDLE;
try {
MemorySegment _result = arena.allocate($LAYOUT);
if (SwiftKit.TRACE_DOWNCALLS) {
SwiftKit.traceDowncall(\(renderForwardJavaParams(decl, paramPassingStyle: nil)));
}
mh$.invokeExact(
\(renderForwardJavaParams(decl, paramPassingStyle: nil)),
/* indirect return buffer */_result
);
return _result;
} catch (Throwable ex$) {
throw new AssertionError("should not reach here", ex$);
}
}, arena);
}
"""
)
}
public func printFunctionDowncallMethods(_ printer: inout CodePrinter, _ decl: ImportedFunc) {
printer.printSeparator(decl.identifier)
printer.printTypeDecl("private static class \(decl.baseIdentifier)") { printer in
printFunctionDescriptorValue(&printer, decl)
printAccessorFunctionAddr(&printer, decl)
printMethodDowncallHandleForAddrDesc(&printer)
}
printFunctionDescriptorMethod(&printer, decl: decl)
printFunctionMethodHandleMethod(&printer, decl: decl)
printFunctionAddressMethod(&printer, decl: decl)
// Render the basic "make the downcall" function
if decl.hasParent {
printFuncDowncallMethod(&printer, decl: decl, paramPassingStyle: .memorySegment)
printFuncDowncallMethod(&printer, decl: decl, paramPassingStyle: .wrapper)
} else {
printFuncDowncallMethod(&printer, decl: decl, paramPassingStyle: nil)
}
}
private func printFunctionAddressMethod(
_ printer: inout CodePrinter,
decl: ImportedFunc,
accessorKind: VariableAccessorKind? = nil
) {
let addrName = accessorKind.renderAddrFieldName
let methodNameSegment = accessorKind.renderMethodNameSegment
let snippet = decl.renderCommentSnippet ?? "* "
printer.print(
"""
/**
* Address for:
\(snippet)
*/
public static MemorySegment \(decl.baseIdentifier)\(methodNameSegment)$address() {
return \(decl.baseIdentifier).\(addrName);
}
"""
)
}
private func printFunctionMethodHandleMethod(
_ printer: inout CodePrinter,
decl: ImportedFunc,
accessorKind: VariableAccessorKind? = nil
) {
let handleName = accessorKind.renderHandleFieldName
let methodNameSegment = accessorKind.renderMethodNameSegment
let snippet = decl.renderCommentSnippet ?? "* "
printer.print(
"""
/**
* Downcall method handle for:
\(snippet)
*/
public static MethodHandle \(decl.baseIdentifier)\(methodNameSegment)$handle() {
return \(decl.baseIdentifier).\(handleName);
}
"""
)
}
private func printFunctionDescriptorMethod(
_ printer: inout CodePrinter,
decl: ImportedFunc,
accessorKind: VariableAccessorKind? = nil
) {
let descName = accessorKind.renderDescFieldName
let methodNameSegment = accessorKind.renderMethodNameSegment
let snippet = decl.renderCommentSnippet ?? "* "
printer.print(
"""
/**
* Function descriptor for:
\(snippet)
*/
public static FunctionDescriptor \(decl.baseIdentifier)\(methodNameSegment)$descriptor() {
return \(decl.baseIdentifier).\(descName);
}
"""
)
}
public func printVariableDowncallMethods(_ printer: inout CodePrinter, _ decl: ImportedVariable) {
printer.printSeparator(decl.identifier)
printer.printTypeDecl("private static class \(decl.baseIdentifier)") { printer in
for accessorKind in decl.supportedAccessorKinds {
guard let accessor = decl.accessorFunc(kind: accessorKind) else {
log.warning("Skip print for \(accessorKind) of \(decl.identifier)!")
continue
}
printFunctionDescriptorValue(&printer, accessor, accessorKind: accessorKind)
printAccessorFunctionAddr(&printer, accessor, accessorKind: accessorKind)
printMethodDowncallHandleForAddrDesc(&printer, accessorKind: accessorKind)
}
}
// First print all the supporting infra
for accessorKind in decl.supportedAccessorKinds {
guard let accessor = decl.accessorFunc(kind: accessorKind) else {
log.warning("Skip print for \(accessorKind) of \(decl.identifier)!")
continue
}
printFunctionDescriptorMethod(&printer, decl: accessor, accessorKind: accessorKind)
printFunctionMethodHandleMethod(&printer, decl: accessor, accessorKind: accessorKind)
printFunctionAddressMethod(&printer, decl: accessor, accessorKind: accessorKind)
}
// Then print the actual downcall methods
for accessorKind in decl.supportedAccessorKinds {
guard let accessor = decl.accessorFunc(kind: accessorKind) else {
log.warning("Skip print for \(accessorKind) of \(decl.identifier)!")
continue
}
// Render the basic "make the downcall" function
if decl.hasParent {
printFuncDowncallMethod(
&printer, decl: accessor, paramPassingStyle: .memorySegment, accessorKind: accessorKind)
printFuncDowncallMethod(
&printer, decl: accessor, paramPassingStyle: .wrapper, accessorKind: accessorKind)
} else {
printFuncDowncallMethod(
&printer, decl: accessor, paramPassingStyle: nil, accessorKind: accessorKind)
}
}
}
func printAccessorFunctionAddr(
_ printer: inout CodePrinter, _ decl: ImportedFunc,
accessorKind: VariableAccessorKind? = nil
) {
let thunkName = thunkNameRegistry.functionThunkName(module: self.swiftModuleName, decl: decl)
printer.print(
"""
public static final MemorySegment \(accessorKind.renderAddrFieldName) =
\(self.swiftModuleName).findOrThrow("\(thunkName)");
"""
)
}
func printMethodDowncallHandleForAddrDesc(
_ printer: inout CodePrinter, accessorKind: VariableAccessorKind? = nil
) {
printer.print(
"""
public static final MethodHandle \(accessorKind.renderHandleFieldName) = Linker.nativeLinker().downcallHandle(\(accessorKind.renderAddrFieldName), \(accessorKind.renderDescFieldName));
"""
)
}
public func printFuncDowncallMethod(
_ printer: inout CodePrinter,
decl: ImportedFunc,
paramPassingStyle: SelfParameterVariant?,
accessorKind: VariableAccessorKind? = nil
) {
let returnTy = decl.returnType.javaType
let maybeReturnCast: String
if decl.returnType.javaType == .void {
maybeReturnCast = "" // nothing to return or cast to
} else {
maybeReturnCast = "return (\(returnTy))"
}
// TODO: we could copy the Swift method's documentation over here, that'd be great UX
let javaDocComment: String =
"""
/**
* Downcall to Swift:
\(decl.renderCommentSnippet ?? "* ")
*/
"""
// An identifier may be "getX", "setX" or just the plain method name
let identifier = accessorKind.renderMethodName(decl)
if paramPassingStyle == SelfParameterVariant.wrapper {
let guardFromDestroyedObjectCalls: String =
if decl.hasParent {
"""
$ensureAlive();
"""
} else { "" }
// delegate to the MemorySegment "self" accepting overload
printer.print(
"""
\(javaDocComment)
public \(returnTy) \(identifier)(\(renderJavaParamDecls(decl, paramPassingStyle: .wrapper))) {
\(guardFromDestroyedObjectCalls)
\(maybeReturnCast) \(identifier)(\(renderForwardJavaParams(decl, paramPassingStyle: .wrapper)));
}
"""
)
return
}
let needsArena = downcallNeedsConfinedArena(decl)
let handleName = accessorKind.renderHandleFieldName
printer.printParts(
"""
\(javaDocComment)
public static \(returnTy) \(identifier)(\(renderJavaParamDecls(decl, paramPassingStyle: paramPassingStyle))) {
var mh$ = \(decl.baseIdentifier).\(handleName);
\(renderTry(withArena: needsArena))
""",
renderUpcallHandles(decl),
renderParameterDowncallConversions(decl),
"""
if (SwiftKit.TRACE_DOWNCALLS) {
SwiftKit.traceDowncall(\(renderForwardJavaParams(decl, paramPassingStyle: .memorySegment)));
}
\(maybeReturnCast) mh$.invokeExact(\(renderForwardJavaParams(decl, paramPassingStyle: paramPassingStyle)));
} catch (Throwable ex$) {
throw new AssertionError("should not reach here", ex$);
}
}
"""
)
}
public func printPropertyAccessorDowncallMethod(
_ printer: inout CodePrinter,
decl: ImportedFunc,
paramPassingStyle: SelfParameterVariant?
) {
let returnTy = decl.returnType.javaType
let maybeReturnCast: String
if decl.returnType.javaType == .void {
maybeReturnCast = "" // nothing to return or cast to
} else {
maybeReturnCast = "return (\(returnTy))"
}
if paramPassingStyle == SelfParameterVariant.wrapper {
// delegate to the MemorySegment "self" accepting overload
printer.print(
"""
/**
* {@snippet lang=swift :
* \(/*TODO: make a printSnippet func*/decl.syntax ?? "")
* }
*/
public \(returnTy) \(decl.baseIdentifier)(\(renderJavaParamDecls(decl, paramPassingStyle: .wrapper))) {
\(maybeReturnCast) \(decl.baseIdentifier)(\(renderForwardJavaParams(decl, paramPassingStyle: .wrapper)));
}
"""
)
return
}
printer.print(
"""
/**
* {@snippet lang=swift :
* \(/*TODO: make a printSnippet func*/decl.syntax ?? "")
* }
*/
public static \(returnTy) \(decl.baseIdentifier)(\(renderJavaParamDecls(decl, paramPassingStyle: paramPassingStyle))) {
var mh$ = \(decl.baseIdentifier).HANDLE;
try {
if (SwiftKit.TRACE_DOWNCALLS) {
SwiftKit.traceDowncall(\(renderForwardJavaParams(decl, paramPassingStyle: .memorySegment)));
}
\(maybeReturnCast) mh$.invokeExact(\(renderForwardJavaParams(decl, paramPassingStyle: paramPassingStyle)));
} catch (Throwable ex$) {
throw new AssertionError("should not reach here", ex$);
}
}
"""
)
}
/// Given a function like `init(cap:name:)`, renders a name like `init_cap_name`
public func renderDescClassName(_ decl: ImportedFunc) -> String {
var ps: [String] = [decl.baseIdentifier]
var pCounter = 0
func nextUniqueParamName() -> String {
pCounter += 1
return "p\(pCounter)"
}
for p in decl.effectiveParameters(paramPassingStyle: nil) {
let param = "\(p.effectiveName ?? nextUniqueParamName())"
ps.append(param)
}
let res = ps.joined(separator: "_")
return res
}
/// Do we need to construct an inline confined arena for the duration of the downcall?
public func downcallNeedsConfinedArena(_ decl: ImportedFunc) -> Bool {
for p in decl.parameters {
// We need to detect if any of the parameters is a closure we need to prepare
// an upcall handle for.
if p.type.javaType.isSwiftClosure {
return true
}
if p.type.javaType.isString {
return true
}
}
return false
}
public func renderTry(withArena: Bool) -> String {
if withArena {
"try (var arena = Arena.ofConfined()) {"
} else {
"try {"
}
}
public func renderJavaParamDecls(_ decl: ImportedFunc, paramPassingStyle: SelfParameterVariant?) -> String {
var ps: [String] = []
var pCounter = 0
func nextUniqueParamName() -> String {
pCounter += 1
return "p\(pCounter)"
}
for p in decl.effectiveParameters(paramPassingStyle: paramPassingStyle) {
let param = "\(p.type.javaType.description) \(p.effectiveName ?? nextUniqueParamName())"
ps.append(param)
}
let res = ps.joined(separator: ", ")
return res
}
// TODO: these are stateless, find new place for them?
public func renderSwiftParamDecls(
_ decl: ImportedFunc,
paramPassingStyle: SelfParameterVariant?,
style: ParameterVariant? = nil
) -> String {
var ps: [String] = []
var pCounter = 0
func nextUniqueParamName() -> String {
pCounter += 1
return "p\(pCounter)"
}
for p in decl.effectiveParameters(paramPassingStyle: paramPassingStyle) {
let firstName = p.firstName ?? "_"
let secondName = p.secondName ?? p.firstName ?? nextUniqueParamName()
let paramTy: String =
if style == .cDeclThunk, p.type.javaType.isString {
"UnsafeMutablePointer<CChar>" // TODO: is this ok?
} else if paramPassingStyle == .swiftThunkSelf {
"\(p.type.cCompatibleSwiftType)"
} else {
p.type.swiftTypeName.description
}
let param =
if firstName == secondName {
// We have to do this to avoid a 'extraneous duplicate parameter name; 'number' already has an argument label' warning
"\(firstName): \(paramTy)"
} else {
"\(firstName) \(secondName): \(paramTy)"
}
ps.append(param)
}
if paramPassingStyle == .swiftThunkSelf {
ps.append("_self: UnsafeMutableRawPointer")
}
let res = ps.joined(separator: ", ")
return res
}
public func renderUpcallHandles(_ decl: ImportedFunc) -> String {
var printer = CodePrinter()
for p in decl.parameters where p.type.javaType.isSwiftClosure {
if p.type.javaType == .javaLangRunnable {
let paramName = p.secondName ?? p.firstName ?? "_"
let handleDesc = p.type.javaType.prepareClosureDowncallHandle(
decl: decl, parameter: paramName)
printer.print(handleDesc)
}
}
return printer.contents
}
public func renderParameterDowncallConversions(_ decl: ImportedFunc) -> String {
var printer = CodePrinter()
for p in decl.parameters {
if p.type.javaType.isString {
printer.print(
"""
var \(p.effectiveValueName)$ = arena.allocateFrom(\(p.effectiveValueName));
"""
)
}
}
return printer.contents
}
public func renderForwardJavaParams(
_ decl: ImportedFunc, paramPassingStyle: SelfParameterVariant?
) -> String {
var ps: [String] = []
var pCounter = 0
func nextUniqueParamName() -> String {
pCounter += 1
return "p\(pCounter)"
}
for p in decl.effectiveParameters(paramPassingStyle: paramPassingStyle) {
// FIXME: fix the handling here we're already a memory segment
let param: String
if p.effectiveName == "self$" {
precondition(paramPassingStyle == .memorySegment)
param = "self$"
} else if p.type.javaType.isString {
// TODO: make this less one-off and maybe call it "was adapted"?
if paramPassingStyle == .wrapper {
// pass it raw, we're not performing adaptation here it seems as we're passing wrappers around
param = "\(p.effectiveValueName)"
} else {
param = "\(p.effectiveValueName)$"
}
} else {
param = "\(p.renderParameterForwarding() ?? nextUniqueParamName())"
}
ps.append(param)
}
// Add the forwarding "self"
if paramPassingStyle == .wrapper && !decl.isInit {
ps.append("$memorySegment()")
}
return ps.joined(separator: ", ")
}
// TODO: these are stateless, find new place for them?
public func renderForwardSwiftParams(
_ decl: ImportedFunc, paramPassingStyle: SelfParameterVariant?
) -> String {
var ps: [String] = []
for p in decl.effectiveParameters(paramPassingStyle: paramPassingStyle) {
if let firstName = p.firstName {
ps.append("\(firstName): \(p.effectiveValueName)")
} else {
ps.append("\(p.effectiveValueName)")
}
}
return ps.joined(separator: ", ")
}
public func printFunctionDescriptorValue(
_ printer: inout CodePrinter,
_ decl: ImportedFunc,
accessorKind: VariableAccessorKind? = nil
) {
let fieldName = accessorKind.renderDescFieldName
printer.start("public static final FunctionDescriptor \(fieldName) = ")
let isIndirectReturn = decl.isIndirectReturn
let parameterLayoutDescriptors: [ForeignValueLayout] = javaMemoryLayoutDescriptors(
forParametersOf: decl,
paramPassingStyle: .pointer
)
if decl.returnType.javaType == .void || isIndirectReturn {
printer.print("FunctionDescriptor.ofVoid(")
printer.indent()
} else {
printer.print("FunctionDescriptor.of(")
printer.indent()
// Write return type
let returnTyIsLastTy = decl.parameters.isEmpty && !decl.hasParent
if decl.isInit {
// when initializing, we return a pointer to the newly created object
printer.print(
"/* -> */\(ForeignValueLayout.SwiftPointer)", .parameterNewlineSeparator(returnTyIsLastTy)
)
} else {
var returnDesc = decl.returnType.foreignValueLayout
returnDesc.inlineComment = " -> "
printer.print(returnDesc, .parameterNewlineSeparator(returnTyIsLastTy))
}
}
// Write all parameters (including synthesized ones, like self)
for (desc, isLast) in parameterLayoutDescriptors.withIsLast {
printer.print(desc, .parameterNewlineSeparator(isLast))
}
printer.outdent()
printer.print(");")
}