forked from swiftlang/swift-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWrapJavaCommand.swift
More file actions
400 lines (330 loc) · 14.7 KB
/
WrapJavaCommand.swift
File metadata and controls
400 lines (330 loc) · 14.7 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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2024-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 ArgumentParser
import Foundation
import JavaUtilJar
import Logging
import SwiftJava
import SwiftJavaConfigurationShared
import SwiftJavaToolLib
extension SwiftJava {
struct WrapJavaCommand: SwiftJavaBaseAsyncParsableCommand, HasCommonOptions, HasCommonJVMOptions {
static let log: Logging.Logger = .init(label: "swift-java:\(configuration.commandName!)")
static let configuration = CommandConfiguration(
commandName: "wrap-java",
abstract: "Wrap Java classes with corresponding Swift bindings."
)
@OptionGroup var commonOptions: SwiftJava.CommonOptions
@OptionGroup var commonJVMOptions: SwiftJava.CommonJVMOptions
@Option(help: "The name of the Swift module into which the resulting Swift types will be generated.")
var swiftModule: String
var effectiveSwiftModule: String {
swiftModule
}
@Option(
help: """
A swift-java configuration file for a given Swift module name on which this module depends,
e.g., JavaKitJar=Sources/JavaKitJar/swift-java.config. There should be one of these options
for each Swift module that this module depends on (transitively) that contains wrapped Java sources.
"""
)
var dependsOn: [String] = []
@Option(help: "The names of Java classes whose declared native methods will be implemented in Swift.")
var swiftNativeImplementation: [String] = []
@Option(help: "Cache directory for intermediate results and other outputs between runs")
var cacheDirectory: String?
@Option(help: "Match java package directory structure with generated Swift files")
var swiftMatchPackageDirectoryStructure: Bool = false
@Option(help: "If specified, a single Swift file will be generated containing all the generated code")
var singleSwiftFileOutput: String?
@Option(name: .long, help: "While scanning a classpath, inspect ONLY types included in these packages")
var filterInclude: [String] = []
@Option(
name: .long,
help:
"While scanning a classpath, skip types which match the filter prefix. You can exclude specific methods by using the `com.example.MyClass#method` format."
)
var filterExclude: [String] = []
@Option(name: .customLong("android-api-version-file"), help: "Path to Android api-versions.xml for generating @available attributes based on API level data")
var androidAPIVersionFile: String?
}
}
extension SwiftJava.WrapJavaCommand {
struct NamedDependentConfig {
let swiftModuleName: String
let configuration: Configuration
}
mutating func runSwiftJavaCommand(config: inout Configuration) async throws {
print("self.filterInclude = \(self.filterInclude)")
configure(&config.javaFilterInclude, append: self.filterInclude)
configure(&config.javaFilterExclude, append: self.filterExclude)
configure(&config.singleSwiftFileOutput, overrideWith: self.singleSwiftFileOutput)
// Get base classpath configuration for this target and configuration
var classpathSearchDirs = [self.effectiveSwiftModuleURL]
if let cacheDir = self.cacheDirectory {
print("[trace][swift-java] Cache directory: \(cacheDir)")
classpathSearchDirs += [URL(fileURLWithPath: cacheDir)]
} else {
print("[trace][swift-java] Cache directory: none")
}
var classpathEntries = self.configureCommandJVMClasspath(
searchDirs: classpathSearchDirs,
config: config,
log: Self.log
)
// Load all of the dependent configurations and associate them with Swift modules.
let dependentConfigs = try loadDependentConfigs(dependsOn: self.dependsOn).map { dependentConfig in
guard let moduleName = dependentConfig.swiftModuleName else {
throw JavaToSwiftError.badConfigOption(self.dependsOn.joined(separator: " "))
}
return NamedDependentConfig(swiftModuleName: moduleName, configuration: dependentConfig.configuration)
}
print("[debug][swift-java] Dependent configs: \(dependentConfigs.count)")
// Include classpath entries which libs we depend on require...
for dependentConfig in dependentConfigs {
print(
"[trace][swift-java] Add dependent config (\(dependentConfig.swiftModuleName)) classpath elements: \(dependentConfig.configuration.classpathEntries.count)"
)
// TODO: may need to resolve the dependent configs rather than just get their configs
// TODO: We should cache the resolved classpaths as well so we don't do it many times
for entry in dependentConfig.configuration.classpathEntries {
print("[trace][swift-java] Add dependent config (\(dependentConfig.swiftModuleName)) classpath element: \(entry)")
classpathEntries.append(entry)
}
}
let jvm = try self.makeJVM(classpathEntries: classpathEntries)
try self.generateWrappers(
config: config,
// classpathEntries: classpathEntries,
dependentConfigs: dependentConfigs,
environment: jvm.environment()
)
}
}
extension SwiftJava.WrapJavaCommand {
mutating func generateWrappers(
config: Configuration,
dependentConfigs: [NamedDependentConfig],
environment: JNIEnvironment
) throws {
let translator = JavaTranslator(
config: config,
swiftModuleName: effectiveSwiftModule,
environment: environment,
translateAsClass: true
)
log.info("Active include filters: \(config.javaFilterInclude ?? [])")
log.info("Active exclude filters: \(config.javaFilterExclude ?? [])")
// Keep track of all of the Java classes that will have
// Swift-native implementations.
translator.swiftNativeImplementations = Set(swiftNativeImplementation)
// Load Android API version data if provided.
if let androidAPIVersionFile {
let url = URL(fileURLWithPath: androidAPIVersionFile)
let apiVersions = try AndroidAPIVersionsParser.parse(contentsOf: url, log: Self.log)
translator.androidAPIVersions = apiVersions
log.info("Loaded Android API versions: \(apiVersions.stats())")
}
// Note all of the dependent configurations.
for dependentConfig in dependentConfigs {
translator.addConfiguration(
dependentConfig.configuration,
forSwiftModule: dependentConfig.swiftModuleName
)
}
// Add the configuration for this module.
translator.addConfiguration(config, forSwiftModule: effectiveSwiftModule)
// Load all of the explicitly-requested classes.
let classLoader = try! JavaClass<ClassLoader>(environment: environment)
.getSystemClassLoader()!
var javaClasses: [JavaClass<JavaObject>] = []
for (javaClassName, _) in config.classes ?? [:] {
func remove() {
translator.translatedClasses.removeValue(forKey: javaClassName)
}
guard shouldImportJavaClass(javaClassName, config: config) else {
remove()
continue
}
guard let javaClass = try classLoader.loadClass(javaClassName) else {
log.warning("Could not load Java class '\(javaClassName)', skipping.")
remove()
continue
}
guard self.shouldExtract(javaClass: javaClass, config: config) else {
log.info("Skip Java type: \(javaClassName) (does not match minimum access level)")
remove()
continue
}
guard !javaClass.isEnum() else {
log.info("Skip Java type: \(javaClassName) (enums do not currently work)")
remove()
continue
}
log.info("Wrapping java type: \(javaClassName)")
// Add this class to the list of classes we'll translate.
javaClasses.append(javaClass)
}
log.info("OK now we go to nested classes")
// Find all of the nested classes for each class, adding them to the list
// of classes to be translated if they were already specified.
var allClassesToVisit = javaClasses
var currentClassIndex: Int = 0
outerClassLoop: while currentClassIndex < allClassesToVisit.count {
defer {
currentClassIndex += 1
}
// The current top-level class we're in.
let currentClass = allClassesToVisit[currentClassIndex]
let currentClassName = currentClass.getName()
guard let currentSwiftName = translator.translatedClasses[currentClass.getName()]?.swiftType else {
continue
}
// Find all of the nested classes that weren't explicitly translated already.
let nestedAndSuperclassNestedClasses = currentClass.getClasses() // watch out, this includes nested types from superclasses
let nestedClasses: [JavaClass<JavaObject>] = nestedAndSuperclassNestedClasses.compactMap { nestedClass in
guard let nestedClass else {
return nil
}
// If this is a local class, we're done.
let javaClassName = nestedClass.getName()
if javaClassName.isLocalJavaClass {
return nil
}
// We only want to visit and import types which are explicitly inside this decl,
// and NOT any of the types contained in the super classes. That would violate our "current class"
// nesting, because those are *actually* nested in the other class, not "the current one" (i.e. in a super class).
guard javaClassName.hasPrefix(currentClassName) else {
log.trace(
"Skip super-class nested class '\(javaClassName)', is not member of \(currentClassName). Will be visited independently."
)
return nil
}
guard shouldImportJavaClass(javaClassName, config: config) else {
return nil
}
// If this class has been explicitly mentioned, we're done.
guard translator.translatedClasses[javaClassName] == nil else {
return nil
}
guard self.shouldExtract(javaClass: nestedClass, config: config) else {
log.info("Skip Java type: \(javaClassName) (does not match minimum access level)")
return nil
}
guard !nestedClass.isEnum() else {
log.info("Skip Java type: \(javaClassName) (enums do not currently work)")
return nil
}
// Record this as a translated class.
let swiftUnqualifiedName = javaClassName.javaClassNameToCanonicalName
.defaultSwiftNameForJavaClass
let swiftName = "\(currentSwiftName).\(swiftUnqualifiedName)"
let translatedSwiftName = SwiftTypeName(module: nil, name: swiftName)
translator.translatedClasses[javaClassName] = translatedSwiftName
log.debug("Record translated Java class '\(javaClassName)' -> \(translatedSwiftName)")
return nestedClass
}
// If there were no new nested classes, there's nothing to do.
if nestedClasses.isEmpty {
continue
}
// Record all of the nested classes that we will visit.
translator.nestedClasses[currentClass.getName()] = nestedClasses
allClassesToVisit.append(contentsOf: nestedClasses)
}
// Validate configurations before writing any files
try translator.validateClassConfiguration()
// Translate all of the Java classes into Swift classes.
if let singleSwiftFileOutput = config.singleSwiftFileOutput {
translator.startNewFile()
let swiftClassDecls = try javaClasses.flatMap {
try translator.translateClass($0)
}
let importDecls = translator.getImportDecls()
let swiftFileText = """
// Auto-generated by Java-to-Swift wrapper generator.
\(importDecls.map { $0.description }.joined())
\(swiftClassDecls.map { $0.description }.joined(separator: "\n"))
"""
try writeContents(
swiftFileText,
outputDirectory: self.actualOutputDirectory,
to: singleSwiftFileOutput,
description: "Java class translation"
)
} else {
for javaClass in javaClasses {
translator.startNewFile()
let swiftClassDecls = try translator.translateClass(javaClass)
let importDecls = translator.getImportDecls()
let swiftFileText = """
// Auto-generated by Java-to-Swift wrapper generator.
\(importDecls.map { $0.description }.joined())
\(swiftClassDecls.map { $0.description }.joined(separator: "\n"))
"""
var generatedFileOutputDir = self.actualOutputDirectory
if self.swiftMatchPackageDirectoryStructure {
generatedFileOutputDir?.append(path: javaClass.getPackageName().replacing(".", with: "/"))
}
let swiftFileName =
try translator.getSwiftTypeName(javaClass, preferValueTypes: false)
.swiftName.replacing(".", with: "+") + ".swift"
try writeContents(
swiftFileText,
outputDirectory: generatedFileOutputDir,
to: swiftFileName,
description: "Java class '\(javaClass.getName())' translation"
)
}
}
}
/// Determines whether a method should be extracted for translation.
/// Only look at public and protected methods here.
private func shouldExtract<T>(javaClass: JavaClass<T>, config: Configuration) -> Bool {
switch config.effectiveMinimumInputAccessLevelMode {
case .internal:
return javaClass.isPublic || javaClass.isProtected || javaClass.isPackage
case .package:
return javaClass.isPublic || javaClass.isProtected || javaClass.isPackage
case .public:
return javaClass.isPublic || javaClass.isProtected
}
}
private func shouldImportJavaClass(_ javaClassName: String, config: Configuration) -> Bool {
// If we have an inclusive filter, import only types from it
if let includes = config.javaFilterInclude, !includes.isEmpty {
let anyIncludeFilterMatched = includes.contains { include in
if javaClassName.starts(with: include) {
// TODO: lower to trace level
return true
}
log.info("Skip Java type: \(javaClassName) (does not match any include filter)")
return false
}
guard anyIncludeFilterMatched else {
log.info("Skip Java type: \(javaClassName) (does not match any include filter)")
return false
}
}
// If we have an exclude filter, check for it as well
for exclude in config.javaFilterExclude ?? [] {
if javaClassName.starts(with: exclude) {
log.info("Skip Java type: \(javaClassName) (does match exclude filter: \(exclude))")
return false
}
}
// The class matches import filters, if any, and was not excluded.
return true
}
}