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
250 lines (205 loc) · 9.08 KB
/
WrapJavaCommand.swift
File metadata and controls
250 lines (205 loc) · 9.08 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
//===----------------------------------------------------------------------===//
//
// 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 Foundation
import ArgumentParser
import SwiftJavaLib
import JavaKit
import JavaKitJar
import SwiftJavaLib
import JavaKitConfigurationShared
extension SwiftJava {
struct WrapJavaCommand: SwiftJavaBaseAsyncParsableCommand, HasCommonOptions, HasCommonJVMOptions {
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/Java2Swift.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
@Argument(help: "Path to .jar file whose Java classes should be wrapped using Swift bindings")
var input: String
}
}
extension SwiftJava.WrapJavaCommand {
mutating func runSwiftJavaCommand(config: inout Configuration) async throws {
// 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")
}
print("[trace][swift-java] INPUT: \(input)")
var classpathEntries = self.configureCommandJVMClasspath(
searchDirs: classpathSearchDirs, config: config)
// Load all of the dependent configurations and associate them with Swift modules.
let dependentConfigs = try self.loadDependentConfigs()
print("[debug][swift-java] Dependent configs: \(dependentConfigs.count)")
// Include classpath entries which libs we depend on require...
for (fromModule, config) in dependentConfigs {
print("[trace][swift-java] Add dependent config (\(fromModule)) classpath elements: \(config.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 config.classpathEntries {
print("[trace][swift-java] Add dependent config (\(fromModule)) 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 {
/// Load all dependent configs configured with `--depends-on` and return a list of
/// `(SwiftModuleName, Configuration)` tuples.
func loadDependentConfigs() throws -> [(String, Configuration)] {
try dependsOn.map { dependentConfig in
guard let equalLoc = dependentConfig.firstIndex(of: "=") else {
throw JavaToSwiftError.badConfigOption(dependentConfig)
}
let afterEqual = dependentConfig.index(after: equalLoc)
let swiftModuleName = String(dependentConfig[..<equalLoc])
let configFileName = String(dependentConfig[afterEqual...])
let config = try readConfiguration(configPath: URL(fileURLWithPath: configFileName)) ?? Configuration()
return (swiftModuleName, config)
}
}
}
extension SwiftJava.WrapJavaCommand {
mutating func generateWrappers(
config: Configuration,
// classpathEntries: [String],
dependentConfigs: [(String, Configuration)],
environment: JNIEnvironment
) throws {
let translator = JavaTranslator(
swiftModuleName: effectiveSwiftModule,
environment: environment,
translateAsClass: true
)
// Keep track of all of the Java classes that will have
// Swift-native implementations.
translator.swiftNativeImplementations = Set(swiftNativeImplementation)
// Note all of the dependent configurations.
for (swiftModuleName, dependentConfig) in dependentConfigs {
translator.addConfiguration(
dependentConfig,
forSwiftModule: 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 ?? [:] {
guard let javaClass = try classLoader.loadClass(javaClassName) else {
print("warning: could not find Java class '\(javaClassName)'")
continue
}
// Add this class to the list of classes we'll translate.
javaClasses.append(javaClass)
}
// 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
while currentClassIndex < allClassesToVisit.count {
defer {
currentClassIndex += 1
}
// The current class we're in.
let currentClass = allClassesToVisit[currentClassIndex]
guard let currentSwiftName = translator.translatedClasses[currentClass.getName()]?.swiftType else {
continue
}
// Find all of the nested classes that weren't explicitly translated
// already.
let nestedClasses: [JavaClass<JavaObject>] = currentClass.getClasses().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
}
// If this class has been explicitly mentioned, we're done.
if translator.translatedClasses[javaClassName] != nil {
return nil
}
// Record this as a translated class.
let swiftUnqualifiedName = javaClassName.javaClassNameToCanonicalName
.defaultSwiftNameForJavaClass
let swiftName = "\(currentSwiftName).\(swiftUnqualifiedName)"
translator.translatedClasses[javaClassName] = (swiftName, nil)
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.
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"
)
}
}
}