forked from swiftlang/swift-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSwift2Java.swift
More file actions
246 lines (208 loc) · 6.8 KB
/
Swift2Java.swift
File metadata and controls
246 lines (208 loc) · 6.8 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
//===----------------------------------------------------------------------===//
//
// 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 OrderedCollections
import SwiftJavaConfigurationShared
import SwiftJavaShared
import SwiftSyntax
import SwiftSyntaxBuilder
public struct SwiftToJava {
let config: Configuration
let dependentConfigs: [Configuration]
public init(config: Configuration, dependentConfigs: [Configuration]) {
self.config = config
self.dependentConfigs = dependentConfigs
}
public func run() throws {
guard let swiftModule = config.swiftModule else {
fatalError("Missing '--swift-module' name.")
}
let translator = Swift2JavaTranslator(config: config)
let log = translator.log
if config.javaPackage == nil || config.javaPackage!.isEmpty {
translator.log.warning(
"Configured java package is '', consider specifying concrete package for generated sources."
)
}
guard let inputSwift = config.inputSwiftDirectory else {
fatalError("Missing '--swift-input' directory!")
}
log.info("Input swift = \(inputSwift)")
let inputPaths = inputSwift.split(separator: ",").map { URL(string: String($0))! }
log.info("Input paths = \(inputPaths)")
let allFiles = collectAllFiles(suffix: ".swift", in: inputPaths, log: translator.log)
let hasFilters =
!(config.swiftFilterInclude ?? []).isEmpty || !(config.swiftFilterExclude ?? []).isEmpty
// Register files to the translator.
let fileManager = FileManager.default
for file in allFiles {
guard canExtract(from: file) else {
continue
}
// Apply jextract include/exclude filters if configured
if hasFilters {
let relativePath = computeRelativePath(file: file, inputPaths: inputPaths)
guard shouldJExtractFile(relativePath: relativePath, config: config) else {
log.info("Skipping file (filtered out): \(file.path)")
translator.filteredOutPaths.append(file.path)
continue
}
}
guard let data = fileManager.contents(atPath: file.path) else {
continue
}
guard let text = String(data: data, encoding: .utf8) else {
continue
}
translator.add(filePath: file.path, text: text)
}
guard let outputSwiftDirectory = config.outputSwiftDirectory else {
fatalError("Missing --output-swift directory!")
}
guard let outputJavaDirectory = config.outputJavaDirectory else {
fatalError("Missing --output-java directory!")
}
let wrappedJavaClassesLookupTable: JavaClassLookupTable = dependentConfigs.compactMap(\.classes).reduce(into: [:]) {
for (canonicalName, javaClass) in $1 {
$0[javaClass] = canonicalName
}
}
translator.dependenciesClasses = Array(wrappedJavaClassesLookupTable.keys)
try translator.analyze()
switch config.effectiveMode {
case .ffm:
let generator = FFMSwift2JavaGenerator(
config: self.config,
translator: translator,
javaPackage: config.javaPackage ?? "",
swiftOutputDirectory: outputSwiftDirectory,
javaOutputDirectory: outputJavaDirectory
)
try generator.generate()
case .jni:
let generator = JNISwift2JavaGenerator(
config: self.config,
translator: translator,
javaPackage: config.javaPackage ?? "",
swiftOutputDirectory: outputSwiftDirectory,
javaOutputDirectory: outputJavaDirectory,
javaClassLookupTable: wrappedJavaClassesLookupTable
)
try generator.generate()
}
print("[swift-java] Imported Swift module '\(swiftModule)': " + "done.".green)
}
func canExtract(from file: URL) -> Bool {
guard file.lastPathComponent.hasSuffix(".swift") || file.lastPathComponent.hasSuffix(".swiftinterface") else {
return false
}
if file.lastPathComponent.hasSuffix("+SwiftJava.swift") {
return false
}
return true
}
/// Compute a relative path (sans `.swift` extension) for a file against the
/// input paths, suitable for jextract filter matching
func computeRelativePath(file: URL, inputPaths: [URL]) -> String {
let filePath = file.standardizedFileURL.path
for inputPath in inputPaths {
let basePath = inputPath.standardizedFileURL.path
let baseWithSlash = basePath.hasSuffix("/") ? basePath : basePath + "/"
if filePath.hasPrefix(baseWithSlash) {
let relative = String(filePath.dropFirst(baseWithSlash.count))
return relative
}
}
// Fallback: just the filename
return file.lastPathComponent
}
}
extension URL {
var isDirectory: Bool {
var isDir: ObjCBool = false
_ = FileManager.default.fileExists(atPath: self.path, isDirectory: &isDir)
return isDir.boolValue
}
}
/// Collect all files with given 'suffix', will explore directories recursively.
public func collectAllFiles(suffix: String, in inputPaths: [URL], log: Logger) -> OrderedSet<URL> {
guard !inputPaths.isEmpty else {
return []
}
let fileManager = FileManager.default
var allFiles: OrderedSet<URL> = []
allFiles.reserveCapacity(32) // rough guesstimate
let resourceKeys: [URLResourceKey] = [
.isRegularFileKey,
.isDirectoryKey,
.nameKey,
]
for path in inputPaths {
do {
try collectFilesFromPath(
path,
suffix: suffix,
fileManager: fileManager,
resourceKeys: resourceKeys,
into: &allFiles,
log: log
)
} catch {
log.trace("Failed to collect paths in: \(path), skipping.")
}
}
return allFiles
}
private func collectFilesFromPath(
_ path: URL,
suffix: String,
fileManager: FileManager,
resourceKeys: [URLResourceKey],
into allFiles: inout OrderedSet<URL>,
log: Logger
) throws {
guard fileManager.fileExists(atPath: path.path) else {
return
}
if path.isDirectory {
let enumerator = fileManager.enumerator(
at: path,
includingPropertiesForKeys: resourceKeys,
options: [.skipsHiddenFiles],
errorHandler: { url, error in
true
}
)
guard let enumerator else {
return
}
for case let fileURL as URL in enumerator {
try? collectFilesFromPath(
fileURL,
suffix: suffix,
fileManager: fileManager,
resourceKeys: resourceKeys,
into: &allFiles,
log: log
)
}
}
guard path.isFileURL else {
return
}
guard path.lastPathComponent.hasSuffix(suffix) else {
return
}
allFiles.append(path)
}