forked from swiftlang/swift-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJExtractCommand.swift
More file actions
227 lines (190 loc) · 8.73 KB
/
JExtractCommand.swift
File metadata and controls
227 lines (190 loc) · 8.73 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
//===----------------------------------------------------------------------===//
//
// 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 ArgumentParser
import Foundation
import JExtractSwiftLib
import JavaUtilJar
import SwiftJava
import SwiftJavaConfigurationShared
import SwiftJavaToolLib
/// Extract Java bindings from Swift sources or interface files.
///
/// Example usage:
/// ```
/// > swift-java jextract
// --input-swift Sources/SwiftyBusiness \
/// --output-swift .build/.../outputs/SwiftyBusiness \
/// --output-Java .build/.../outputs/Java
/// ```
extension SwiftJava {
struct JExtractCommand: SwiftJavaBaseAsyncParsableCommand, HasCommonOptions {
static let configuration = CommandConfiguration(
commandName: "jextract", // TODO: wrap-swift?
abstract: "Wrap Swift functions and types with Java bindings, making them available to be called from Java",
)
@OptionGroup var commonOptions: SwiftJava.CommonOptions
@Option(help: "The mode of generation to use for the output files. Used with jextract mode.")
var mode: JExtractGenerationMode?
@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: "The Java package the generated Java code should be emitted into.")
var javaPackage: String? = nil
@Option(help: "The directory where generated Swift files should be written. Generally used with jextract mode.")
var outputSwift: String
@Option(help: "The directory where generated Java files should be written. Generally used with jextract mode.")
var outputJava: String
@Flag(
inversion: .prefixedNo,
help:
"Some build systems require an output to be present when it was 'expected', even if empty. This is used by the JExtractSwiftPlugin build plugin, but otherwise should not be necessary.",
)
var writeEmptyFiles: Bool?
@Option(help: "The lowest access level of Swift declarations that should be extracted, defaults to 'public'.")
var minimumInputAccessLevelMode: JExtractMinimumAccessLevelMode?
@Option(
help:
"The memory management mode to use for the generated code. By default, the user must explicitly provide `SwiftArena` to all calls that require it. By choosing `allowGlobalAutomatic`, user can omit this parameter and a global GC-based arena will be used."
)
var memoryManagementMode: JExtractMemoryManagementMode?
@Option(
help: """
A swift-java configuration file for a given Swift module name on which this module depends,
e.g., Sources/JavaJar/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 mode to use for extracting asynchronous Swift functions. By default async methods are extracted as Java functions returning CompletableFuture."
)
var asyncFuncMode: JExtractAsyncFuncMode?
@Flag(
inversion: .prefixedNo,
help:
"By enabling this mode, JExtract will generate Java code that allows you to implement Swift protocols using Java classes. This feature requires disabling the SwiftPM Sandbox (!). This feature is onl supported in 'jni' mode.",
)
var enableJavaCallbacks: Bool?
@Option(help: "If specified, JExtract will output to this file a list of paths to all generated Java source files")
var generatedJavaSourcesListFileOutput: String?
@Option(
help: """
If specified, JExtract (JNI mode) will write a linker version script to this path. \
The file lists every generated JNI @_cdecl entry-point symbol as a global export \
and hides all other symbols with local: *, enabling dead-code elimination of \
unreachable Swift code:
-Xlinker --version-script=<path>
"""
)
var linkerExportListOutput: String?
@Option(
name: .long,
help: """
Include only Swift source files matching these patterns during jextract. \
Patterns are matched against relative file paths (without .swift extension). \
Supports * (single-segment wildcard) and ** (recursive wildcard). \
Example: --filter-include 'Models/**'
""",
)
var filterInclude: [String] = []
@Option(
name: .long,
help: """
Exclude Swift source files matching these patterns during jextract. \
Same pattern syntax as --filter-include. \
Example: --filter-exclude 'Internal/*'
""",
)
var filterExclude: [String] = []
@Option(help: "If specified, only generate bindings for this single Swift type name")
var singleType: String?
@Option(
help:
"Path to a JSON file containing a StaticBuildConfiguration. Used to resolve #if conditional compilation blocks."
)
var staticBuildConfig: String?
}
}
extension SwiftJava.JExtractCommand {
func runSwiftJavaCommand(config: inout Configuration) async throws {
configure(&config.javaPackage, overrideWith: self.javaPackage)
configure(&config.mode, overrideWith: self.mode)
config.swiftModule = self.effectiveSwiftModule
config.outputJavaDirectory = outputJava
config.outputSwiftDirectory = outputSwift
configure(&config.writeEmptyFiles, overrideWith: writeEmptyFiles)
configure(&config.enableJavaCallbacks, overrideWith: enableJavaCallbacks)
configure(&config.minimumInputAccessLevelMode, overrideWith: self.minimumInputAccessLevelMode)
configure(&config.memoryManagementMode, overrideWith: self.memoryManagementMode)
configure(&config.asyncFuncMode, overrideWith: self.asyncFuncMode)
configure(&config.generatedJavaSourcesListFileOutput, overrideWith: self.generatedJavaSourcesListFileOutput)
configure(&config.linkerExportListOutput, overrideWith: self.linkerExportListOutput)
configure(&config.swiftFilterInclude, append: self.filterInclude)
configure(&config.swiftFilterExclude, append: self.filterExclude)
configure(&config.singleType, overrideWith: self.singleType)
configure(&config.staticBuildConfigurationFile, overrideWith: self.staticBuildConfig)
try checkModeCompatibility(config: config)
if let inputSwift = commonOptions.inputSwift {
config.inputSwiftDirectory = inputSwift
} else if let swiftModule = config.swiftModule {
// This is a "good guess" technically a target can be somewhere else, but then you can use --input-swift
config.inputSwiftDirectory = "\(FileManager.default.currentDirectoryPath)/Sources/\(swiftModule)"
}
print("[debug][swift-java] Running 'swift-java jextract' in mode: " + "\(config.effectiveMode)".bold)
// Load all of the dependent configurations and associate them with Swift modules.
let dependentConfigs = try loadDependentConfigs(dependsOn: self.dependsOn)
print("[debug][swift-java] Dependent configs: \(dependentConfigs.count)")
try jextractSwift(config: config, dependentConfigs: dependentConfigs)
}
/// Check if the configured modes are compatible, and fail if not
func checkModeCompatibility(config: Configuration) throws {
if config.effectiveMode == .ffm {
guard config.effectiveMemoryManagementMode == .explicit else {
throw IllegalModeCombinationError(
"FFM mode does not support '\(self.memoryManagementMode ?? .default)' memory management mode! \(Self.helpMessage())"
)
}
if let enableJavaCallbacks = config.enableJavaCallbacks, enableJavaCallbacks {
throw IllegalModeCombinationError("FFM mode does not support enabling Java callbacks! \(Self.helpMessage())")
}
}
}
}
struct IncompatibleModeError: Error {
let message: String
init(_ message: String) {
self.message = message
}
}
extension SwiftJava.JExtractCommand {
func jextractSwift(
config: Configuration,
dependentConfigs: [DependentConfig],
) throws {
try SwiftToJava(config: config, dependentConfigs: dependentConfigs).run()
}
}
struct IllegalModeCombinationError: Error {
let message: String
init(_ message: String) {
self.message = message
}
}
extension JExtractGenerationMode: ExpressibleByArgument {}
extension JExtractMinimumAccessLevelMode: ExpressibleByArgument {}
extension JExtractMemoryManagementMode: ExpressibleByArgument {}
extension JExtractAsyncFuncMode: ExpressibleByArgument {}