forked from swiftlang/swift-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFFMSwift2JavaGenerator.swift
More file actions
458 lines (391 loc) · 15.1 KB
/
FFMSwift2JavaGenerator.swift
File metadata and controls
458 lines (391 loc) · 15.1 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
//===----------------------------------------------------------------------===//
//
// 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 CodePrinting
import SwiftJavaConfigurationShared
import SwiftJavaJNICore
import SwiftSyntax
import SwiftSyntaxBuilder
import struct Foundation.URL
package class FFMSwift2JavaGenerator: Swift2JavaGenerator {
let log: Logger
let config: Configuration
let analysis: AnalysisResult
let swiftModuleName: String
let javaPackage: String
let swiftOutputDirectory: String
let javaOutputDirectory: String
let lookupContext: SwiftTypeLookupContext
var javaPackagePath: String {
javaPackage.replacingOccurrences(of: ".", with: "/")
}
var thunkNameRegistry: ThunkNameRegistry = ThunkNameRegistry()
/// Cached Java translation result. 'nil' indicates failed translation.
var translatedDecls: [ImportedFunc: TranslatedFunctionDecl?] = [:]
/// Duplicate identifier tracking for the current batch of methods being generated.
var currentJavaIdentifiers: JavaIdentifierFactory = JavaIdentifierFactory()
/// Because we need to write empty files for SwiftPM, keep track which files we didn't write yet,
/// and write an empty file for those.
///
/// Since Swift files in SwiftPM builds needs to be unique, we use this fact to flatten paths into plain names here.
/// For uniqueness checking "did we write this file already", just checking the name should be sufficient.
var expectedOutputSwiftFileNames: Set<String>
package init(
config: Configuration,
translator: Swift2JavaTranslator,
javaPackage: String,
swiftOutputDirectory: String,
javaOutputDirectory: String
) {
self.log = Logger(label: "ffm-generator", logLevel: translator.log.logLevel)
self.config = config
self.analysis = translator.result
self.swiftModuleName = translator.swiftModuleName
self.javaPackage = javaPackage
self.swiftOutputDirectory = swiftOutputDirectory
self.javaOutputDirectory = javaOutputDirectory
self.lookupContext = translator.lookupContext
// If we are forced to write empty files, construct the expected outputs.
// It is sufficient to use file names only, since SwiftPM requires names to be unique within a module anyway.
if translator.config.writeEmptyFiles ?? false {
self.expectedOutputSwiftFileNames = Set(
translator.inputs.compactMap { (input) -> String? in
guard let fileName = input.path.split(separator: PATH_SEPARATOR).last else {
return nil
}
guard fileName.hasSuffix(".swift") else {
return nil
}
return String(fileName.replacing(".swift", with: "+SwiftJava.swift"))
}
)
self.expectedOutputSwiftFileNames.insert("\(translator.swiftModuleName)Module+SwiftJava.swift")
self.expectedOutputSwiftFileNames.insert("Foundation+SwiftJava.swift")
} else {
self.expectedOutputSwiftFileNames = []
}
}
func generate() throws {
try writeSwiftThunkSources()
log.info("Generated Swift sources (module: '\(self.swiftModuleName)') in: \(swiftOutputDirectory)/")
try writeExportedJavaSources()
log.info("Generated Java sources (package: '\(javaPackage)') in: \(javaOutputDirectory)/")
try writeSwiftExpectedEmptySources()
}
}
// ===== --------------------------------------------------------------------------------------------------------------
// MARK: Defaults
extension FFMSwift2JavaGenerator {
/// Default set Java imports for every generated file
static let defaultJavaImports: [String] = [
"org.swift.swiftkit.core.*",
"org.swift.swiftkit.core.util.*",
"org.swift.swiftkit.ffm.*",
// NonNull, Unsigned and friends
"org.swift.swiftkit.core.annotations.*",
// Necessary for native calls and type mapping
"java.lang.foreign.*",
"java.lang.invoke.*",
"java.util.*",
"java.nio.charset.StandardCharsets",
]
}
// ==== ---------------------------------------------------------------------------------------------------------------
// MARK: File writing
extension FFMSwift2JavaGenerator {
package func writeExportedJavaSources() throws {
var printer = CodePrinter()
try writeExportedJavaSources(printer: &printer)
}
/// Every imported public type becomes a public class in its own file in Java.
package func writeExportedJavaSources(printer: inout CodePrinter) throws {
for (_, ty) in analysis.importedTypes.sorted(by: { (lhs, rhs) in lhs.key < rhs.key }) {
let filename = "\(ty.swiftNominal.name).java"
log.debug("Printing contents: \(filename)")
printImportedNominal(&printer, ty)
if let outputFile = try printer.writeContents(
outputDirectory: javaOutputDirectory,
javaPackagePath: javaPackagePath,
filename: filename
) {
log.info("Generated: \((ty.swiftNominal.name.bold + ".java").bold) (at \(outputFile.absoluteString))")
}
}
do {
let filename = "\(self.swiftModuleName).java"
log.debug("Printing contents: \(filename)")
printModule(&printer)
if let outputFile = try printer.writeContents(
outputDirectory: javaOutputDirectory,
javaPackagePath: javaPackagePath,
filename: filename
) {
log.info("Generated: \((self.swiftModuleName + ".java").bold) (at \(outputFile.absoluteString))")
}
}
}
}
// ==== ---------------------------------------------------------------------------------------------------------------
// MARK: Java/text printing
extension FFMSwift2JavaGenerator {
/// 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.
func printModule(_ printer: inout CodePrinter) {
printHeader(&printer)
printPackage(&printer)
printImports(&printer)
self.currentJavaIdentifiers = JavaIdentifierFactory(
self.analysis.importedGlobalFuncs + self.analysis.importedGlobalVariables
)
printModuleClass(&printer) { printer in
for decl in analysis.importedGlobalVariables {
self.log.trace("Print imported decl: \(decl)")
printFunctionDowncallMethods(&printer, decl)
}
for decl in analysis.importedGlobalFuncs {
self.log.trace("Print imported decl: \(decl)")
printFunctionDowncallMethods(&printer, decl)
}
}
}
func printImportedNominal(_ printer: inout CodePrinter, _ decl: ImportedNominalType) {
printHeader(&printer)
printPackage(&printer)
printImports(&printer) // TODO: we could have some imports be driven from types used in the generated decl
self.currentJavaIdentifiers = JavaIdentifierFactory(
decl.initializers + decl.variables + decl.methods
)
printNominal(&printer, decl) { printer in
// 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() {
SwiftLibraries.loadLibraryWithFallbacks(SwiftLibraries.LIB_NAME_SWIFT_CORE);
SwiftLibraries.loadLibraryWithFallbacks(SwiftLibraries.LIB_NAME_SWIFT_JAVA);
SwiftLibraries.loadLibraryWithFallbacks(SwiftLibraries.LIB_NAME_SWIFT_RUNTIME_FUNCTIONS);
SwiftLibraries.loadLibraryWithFallbacks(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("")
printer.print(
"""
private \(decl.swiftNominal.name)(MemorySegment segment, AllocatingSwiftArena arena) {
super(segment, arena);
}
/**
* Assume that the passed {@code MemorySegment} represents a memory address of a {@link \(decl.swiftNominal.name)}.
* <p/>
* Warnings:
* <ul>
* <li>No checks are performed about the compatibility of the pointed at memory and the actual \(decl.swiftNominal.name) 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 \(decl.swiftNominal.name) wrapMemoryAddressUnsafe(MemorySegment selfPointer, AllocatingSwiftArena arena) {
return new \(decl.swiftNominal.name)(selfPointer, arena);
}
"""
)
// Initializers
for initDecl in decl.initializers {
printFunctionDowncallMethods(&printer, initDecl)
}
// Properties
for accessorDecl in decl.variables {
printFunctionDowncallMethods(&printer, accessorDecl)
}
// Methods
for funcDecl in decl.methods {
printFunctionDowncallMethods(&printer, funcDecl)
}
// Special helper methods for known types (e.g. Data)
printSpecificTypeHelpers(&printer, decl)
// Helper methods and default implementations
printToStringMethod(&printer, decl)
}
}
func printHeader(_ printer: inout CodePrinter) {
printer.print(
"""
// Generated by jextract-swift
// Swift module: \(swiftModuleName)
"""
)
}
func printPackage(_ printer: inout CodePrinter) {
printer.print(
"""
package \(javaPackage);
"""
)
}
func printImports(_ printer: inout CodePrinter) {
for i in FFMSwift2JavaGenerator.defaultJavaImports {
printer.print("import \(i);")
}
printer.print("")
}
func printNominal(
_ printer: inout CodePrinter,
_ decl: ImportedNominalType,
body: (inout CodePrinter) -> Void
) {
let parentProtocol: String
if decl.swiftNominal.isReferenceType {
parentProtocol = "SwiftHeapObject"
} else {
parentProtocol = "SwiftValue"
}
if decl.swiftNominal.isSendable {
printer.print("@ThreadSafe // Sendable")
}
printer.printBraceBlock(
"public final class \(decl.swiftNominal.name) extends FFMSwiftInstance implements \(parentProtocol)"
) {
printer in
// Constants
printClassConstants(printer: &printer)
body(&printer)
}
}
func printModuleClass(_ printer: inout CodePrinter, body: (inout CodePrinter) -> Void) {
printer.printBraceBlock("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 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() {
if (SwiftLibraries.AUTO_LOAD_LIBS) {
SwiftLibraries.loadLibraryWithFallbacks(SwiftLibraries.LIB_NAME_SWIFT_CORE);
SwiftLibraries.loadLibraryWithFallbacks(SwiftLibraries.LIB_NAME_SWIFT_JAVA);
SwiftLibraries.loadLibraryWithFallbacks(SwiftLibraries.LIB_NAME_SWIFT_RUNTIME_FUNCTIONS);
SwiftLibraries.loadLibraryWithFallbacks(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)
}
}
func printClassConstants(printer: inout CodePrinter) {
printer.print(
"""
static final String LIB_NAME = "\(swiftModuleName)";
static final Arena LIBRARY_ARENA = Arena.ofAuto();
"""
)
}
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(
"""
public static final GroupLayout $LAYOUT = (GroupLayout) SwiftValueWitnessTable.layoutOfSwiftType(TYPE_METADATA.$memorySegment());
public final GroupLayout $layout() {
return $LAYOUT;
}
"""
)
}
func printToStringMethod(
_ printer: inout CodePrinter,
_ decl: ImportedNominalType
) {
printer.print(
"""
@Override
public String toString() {
return getClass().getSimpleName()
+ "("
+ SwiftRuntime.nameOfSwiftType($swiftType().$memorySegment(), true)
+ ")@"
+ $memorySegment();
}
"""
)
}
/// Print special helper methods for known types like Foundation.Data
func printSpecificTypeHelpers(_ printer: inout CodePrinter, _ decl: ImportedNominalType) {
guard let knownType = decl.swiftNominal.knownTypeKind else {
return
}
switch knownType {
case .foundationData, .essentialsData:
printFoundationDataHelpers(&printer, decl)
default:
break
}
}
}