forked from swiftlang/swift-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSwift2JavaTranslator.swift
More file actions
218 lines (174 loc) · 6.5 KB
/
Swift2JavaTranslator.swift
File metadata and controls
218 lines (174 loc) · 6.5 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
//===----------------------------------------------------------------------===//
//
// 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 JavaTypes
import SwiftBasicFormat
import SwiftParser
import SwiftSyntax
/// Takes swift interfaces and translates them into Java used to access those.
public final class Swift2JavaTranslator {
static let SWIFT_INTERFACE_SUFFIX = ".swiftinterface"
package var log = Logger(label: "translator", logLevel: .info)
// ==== Input
struct Input {
let filePath: String
let syntax: SourceFileSyntax
}
var inputs: [Input] = []
// ==== Output configuration
let javaPackage: String
var javaPackagePath: String {
javaPackage.replacingOccurrences(of: ".", with: "/")
}
// ==== Output state
package var importedGlobalVariables: [ImportedFunc] = []
package var importedGlobalFuncs: [ImportedFunc] = []
/// A mapping from Swift type names (e.g., A.B) over to the imported nominal
/// type representation.
package var importedTypes: [String: ImportedNominalType] = [:]
package var swiftStdlibTypes: SwiftStandardLibraryTypes
package let symbolTable: SwiftSymbolTable
package var thunkNameRegistry: ThunkNameRegistry = ThunkNameRegistry()
/// Cached Java translation result. 'nil' indicates failed translation.
var translatedSignatures: [ImportedFunc: TranslatedFunctionSignature?] = [:]
/// The name of the Swift module being translated.
var swiftModuleName: String {
symbolTable.moduleName
}
public init(
javaPackage: String,
swiftModuleName: String
) {
self.javaPackage = javaPackage
self.symbolTable = SwiftSymbolTable(parsedModuleName: swiftModuleName)
// Create a mock of the Swift standard library.
var parsedSwiftModule = SwiftParsedModuleSymbolTable(moduleName: "Swift")
self.swiftStdlibTypes = SwiftStandardLibraryTypes(into: &parsedSwiftModule)
self.symbolTable.importedModules.append(parsedSwiftModule.symbolTable)
}
}
// ===== --------------------------------------------------------------------------------------------------------------
// MARK: Analysis
extension Swift2JavaTranslator {
/// The primitive Java type to use for Swift's Int type, which follows the
/// size of a pointer.
///
/// FIXME: Consider whether to extract this information from the Swift
/// interface file, so that it would be 'int' for 32-bit targets or 'long' for
/// 64-bit targets but make the Java code different for the two, vs. adding
/// a checked truncation operation at the Java/Swift board.
var javaPrimitiveForSwiftInt: JavaType { .long }
package func add(filePath: String, text: String) {
log.trace("Adding: \(filePath)")
let sourceFileSyntax = Parser.parse(source: text)
self.inputs.append(Input(filePath: filePath, syntax: sourceFileSyntax))
}
/// Convenient method for analyzing single file.
package func analyze(
file: String,
text: String
) throws {
self.add(filePath: file, text: text)
try self.analyze()
}
/// Analyze registered inputs.
func analyze() throws {
prepareForTranslation()
let visitor = Swift2JavaVisitor(
moduleName: self.swiftModuleName,
targetJavaPackage: self.javaPackage,
translator: self
)
for input in self.inputs {
log.trace("Analyzing \(input.filePath)")
visitor.walk(input.syntax)
}
}
package func prepareForTranslation() {
/// Setup the symbol table.
symbolTable.setup(inputs.map({ $0.syntax }))
}
}
// ===== --------------------------------------------------------------------------------------------------------------
// MARK: Defaults
extension Swift2JavaTranslator {
/// Default formatting options.
static let defaultFormat = BasicFormat(indentationWidth: .spaces(2))
/// Default set Java imports for every generated file
static let defaultJavaImports: Array<String> = [
"org.swift.swiftkit.*",
"org.swift.swiftkit.SwiftKit",
"org.swift.swiftkit.util.*",
// Necessary for native calls and type mapping
"java.lang.foreign.*",
"java.lang.invoke.*",
"java.util.Arrays",
"java.util.stream.Collectors",
"java.util.concurrent.atomic.*",
"java.nio.charset.StandardCharsets",
]
}
// ==== ----------------------------------------------------------------------------------------------------------------
// MARK: Type translation
extension Swift2JavaTranslator {
/// Try to resolve the given nominal declaration node into its imported representation.
func importedNominalType(
_ nominalNode: some DeclGroupSyntax & NamedDeclSyntax & WithModifiersSyntax & WithAttributesSyntax,
parent: ImportedNominalType?
) -> ImportedNominalType? {
if !nominalNode.shouldImport(log: log) {
return nil
}
guard let nominal = symbolTable.lookupType(nominalNode.name.text, parent: parent?.swiftNominal) else {
return nil
}
return self.importedNominalType(nominal)
}
/// Try to resolve the given nominal type node into its imported representation.
func importedNominalType(
_ typeNode: TypeSyntax
) -> ImportedNominalType? {
guard let swiftType = try? SwiftType(typeNode, symbolTable: self.symbolTable) else {
return nil
}
guard let swiftNominalDecl = swiftType.asNominalTypeDeclaration else {
return nil
}
// Whether to import this extension?
guard let nominalNode = symbolTable.parsedModule.nominalTypeSyntaxNodes[swiftNominalDecl] else {
return nil
}
guard nominalNode.shouldImport(log: log) else {
return nil
}
return importedNominalType(swiftNominalDecl)
}
func importedNominalType(_ nominal: SwiftNominalTypeDeclaration) -> ImportedNominalType? {
let fullName = nominal.qualifiedName
if let alreadyImported = importedTypes[fullName] {
return alreadyImported
}
let importedNominal = ImportedNominalType(swiftNominal: nominal)
importedTypes[fullName] = importedNominal
return importedNominal
}
}
// ==== ----------------------------------------------------------------------------------------------------------------
// MARK: Errors
public struct Swift2JavaTranslatorError: Error {
let message: String
public init(message: String) {
self.message = message
}
}