forked from swiftlang/swift-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFFMSwift2JavaGenerator+SwiftThunkPrinting.swift
More file actions
231 lines (183 loc) · 7.21 KB
/
FFMSwift2JavaGenerator+SwiftThunkPrinting.swift
File metadata and controls
231 lines (183 loc) · 7.21 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
//===----------------------------------------------------------------------===//
//
// 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 SwiftSyntax
import SwiftSyntaxBuilder
extension FFMSwift2JavaGenerator {
package func writeSwiftThunkSources() throws {
var printer = CodePrinter()
try writeSwiftThunkSources(printer: &printer)
}
package func writeSwiftExpectedEmptySources() throws {
let pendingFileCount = self.expectedOutputSwiftFileNames.count
guard pendingFileCount > 0 else {
return // no need to write any empty files, yay
}
log.info("[swift-java] Write empty [\(self.expectedOutputSwiftFileNames.count)] 'expected' files in: \(swiftOutputDirectory)/")
for expectedFileName in self.expectedOutputSwiftFileNames {
log.info("Write SwiftPM-'expected' empty file: \(expectedFileName.bold)")
var printer = CodePrinter()
printer.print("// Empty file generated on purpose")
_ = try printer.writeContents(
outputDirectory: self.swiftOutputDirectory,
javaPackagePath: nil,
filename: expectedFileName)
}
}
package func writeSwiftThunkSources(printer: inout CodePrinter) throws {
let moduleFilenameBase = "\(self.swiftModuleName)Module+SwiftJava"
let moduleFilename = "\(moduleFilenameBase).swift"
do {
log.debug("Printing contents: \(moduleFilename)")
try printGlobalSwiftThunkSources(&printer)
if let outputFile = try printer.writeContents(
outputDirectory: self.swiftOutputDirectory,
javaPackagePath: nil,
filename: moduleFilename) {
log.info("Generated: \(moduleFilenameBase.bold).swift (at \(outputFile.absoluteString))")
self.expectedOutputSwiftFileNames.remove(moduleFilename)
}
} catch {
log.warning("Failed to write to Swift thunks: \(moduleFilename)")
}
// === All types
// We have to write all types to their corresponding output file that matches the file they were declared in,
// because otherwise SwiftPM plugins will not pick up files apropriately -- we expect 1 output +SwiftJava.swift file for every input.
for group: (key: String, value: [Dictionary<String, ImportedNominalType>.Element]) in Dictionary(grouping: self.analysis.importedTypes, by: { $0.value.sourceFilePath }) {
log.warning("Writing types in file group: \(group.key): \(group.value.map(\.key))")
let importedTypesForThisFile = group.value
.map(\.value)
.sorted(by: { $0.qualifiedName < $1.qualifiedName })
let inputFileName = "\(group.key)".split(separator: "/").last ?? "__Unknown.swift"
let filename = "\(inputFileName)".replacing(".swift", with: "+SwiftJava.swift")
for ty in importedTypesForThisFile {
log.info("Printing Swift thunks for type: \(ty.qualifiedName.bold)")
printer.printSeparator("Thunks for \(ty.qualifiedName)")
do {
try printSwiftThunkSources(&printer, ty: ty)
} catch {
log.warning("Failed to print to Swift thunks for type'\(ty.qualifiedName)' to '\(filename)', error: \(error)")
}
}
log.warning("Write Swift thunks file: \(filename.bold)")
do {
if let outputFile = try printer.writeContents(
outputDirectory: self.swiftOutputDirectory,
javaPackagePath: nil,
filename: filename) {
log.info("Done writing Swift thunks to: \(outputFile.absoluteString)")
self.expectedOutputSwiftFileNames.remove(filename)
}
} catch {
log.warning("Failed to write to Swift thunks: \(filename), error: \(error)")
}
}
}
public func printGlobalSwiftThunkSources(_ printer: inout CodePrinter) throws {
let stt = SwiftThunkTranslator(self)
printer.print(
"""
// Generated by swift-java
import SwiftRuntimeFunctions
""")
self.lookupContext.symbolTable.printImportedModules(&printer)
for thunk in stt.renderGlobalThunks() {
printer.print(thunk)
printer.println()
}
}
public func printSwiftThunkSources(_ printer: inout CodePrinter, decl: ImportedFunc) {
let stt = SwiftThunkTranslator(self)
for thunk in stt.render(forFunc: decl) {
printer.print(thunk)
printer.println()
}
}
package func printSwiftThunkSources(_ printer: inout CodePrinter, ty: ImportedNominalType) throws {
let stt = SwiftThunkTranslator(self)
printer.print(
"""
// Generated by swift-java
import SwiftRuntimeFunctions
"""
)
self.lookupContext.symbolTable.printImportedModules(&printer)
for thunk in stt.renderThunks(forType: ty) {
printer.print("\(thunk)")
printer.print("")
}
}
}
struct SwiftThunkTranslator {
let st: FFMSwift2JavaGenerator
init(_ st: FFMSwift2JavaGenerator) {
self.st = st
}
func renderGlobalThunks() -> [DeclSyntax] {
var decls: [DeclSyntax] = []
decls.reserveCapacity(
st.analysis.importedGlobalVariables.count + st.analysis.importedGlobalFuncs.count
)
for decl in st.analysis.importedGlobalVariables {
decls.append(contentsOf: render(forFunc: decl))
}
for decl in st.analysis.importedGlobalFuncs {
decls.append(contentsOf: render(forFunc: decl))
}
return decls
}
/// Render all the thunks that make Swift methods accessible to Java.
func renderThunks(forType nominal: ImportedNominalType) -> [DeclSyntax] {
var decls: [DeclSyntax] = []
decls.reserveCapacity(
1 + nominal.initializers.count + nominal.variables.count + nominal.methods.count
)
decls.append(renderSwiftTypeAccessor(nominal))
for decl in nominal.initializers {
decls.append(contentsOf: render(forFunc: decl))
}
for decl in nominal.variables {
decls.append(contentsOf: render(forFunc: decl))
}
for decl in nominal.methods {
decls.append(contentsOf: render(forFunc: decl))
}
return decls
}
/// Accessor to get the `T.self` of the Swift type, without having to rely on mangled name lookups.
func renderSwiftTypeAccessor(_ nominal: ImportedNominalType) -> DeclSyntax {
let funcName = SwiftKitPrinting.Names.getType(
module: st.swiftModuleName,
nominal: nominal)
return
"""
@_cdecl("\(raw: funcName)")
public func \(raw: funcName)() -> UnsafeMutableRawPointer /* Any.Type */ {
return unsafeBitCast(\(raw: nominal.swiftNominal.qualifiedName).self, to: UnsafeMutableRawPointer.self)
}
"""
}
func render(forFunc decl: ImportedFunc) -> [DeclSyntax] {
st.log.trace("Rendering thunks for: \(decl.displayName)")
let thunkName = st.thunkNameRegistry.functionThunkName(decl: decl)
guard let translated = st.translatedDecl(for: decl) else {
return []
}
let thunkFunc = translated.loweredSignature.cdeclThunk(
cName: thunkName,
swiftAPIName: decl.name,
as: decl.apiKind
)
return [DeclSyntax(thunkFunc)]
}
}