Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 23 additions & 2 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,11 @@ let package = Package(
targets: ["JavaKit"]
),

.library(
name: "JavaRuntime",
targets: [ "JavaRuntime"]
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
targets: [ "JavaRuntime"]
targets: ["JavaRuntime"]

Need to enable the Swift formatting enforcement soon 🤔

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Eh, sure

),

.library(
name: "JavaKitJar",
targets: ["JavaKitReflection"]
Expand Down Expand Up @@ -83,7 +88,7 @@ let package = Package(

.executable(
name: "Java2Swift",
targets: ["Java2SwiftTool"]
targets: ["Java2Swift"]
),

// ==== Plugin for building Java code
Expand All @@ -94,6 +99,14 @@ let package = Package(
]
),

// ==== Plugin for wrapping Java classes in Swift
.plugin(
name: "Java2SwiftPlugin",
targets: [
"Java2SwiftPlugin"
]
),

// ==== jextract-swift (extract Java accessors from Swift interface files)

.executable(
Expand Down Expand Up @@ -206,6 +219,14 @@ let package = Package(
capability: .buildTool()
),

.plugin(
name: "Java2SwiftPlugin",
capability: .buildTool(),
dependencies: [
"Java2Swift"
]
),

.target(
name: "ExampleSwiftLibrary",
dependencies: [],
Expand Down Expand Up @@ -251,7 +272,7 @@ let package = Package(
),

.executableTarget(
name: "Java2SwiftTool",
name: "Java2Swift",
dependencies: [
.product(name: "SwiftBasicFormat", package: "swift-syntax"),
.product(name: "SwiftSyntax", package: "swift-syntax"),
Expand Down
26 changes: 26 additions & 0 deletions Plugins/Java2SwiftPlugin/Configuration.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//

/// Configuration for the Java2Swift translation tool, provided on a per-target
/// basis.
struct Configuration: Codable {
/// The Java class path that should be passed along to the Java2Swift tool.
var classPath: String? = nil

/// The Java classes that should be translated to Swift. The keys are
/// canonical Java class names (e.g., java.util.Vector) and the values are
/// the corresponding Swift names (e.g., JavaVector). If the value is `nil`,
/// then the Java class name will be used for the Swift name, too.
var classes: [String: String?] = [:]
}
154 changes: 154 additions & 0 deletions Plugins/Java2SwiftPlugin/Java2SwiftPlugin.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
//===----------------------------------------------------------------------===//
//
// 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 PackagePlugin

@main
struct Java2SwiftBuildToolPlugin: BuildToolPlugin {
func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] {
guard let sourceModule = target.sourceModule else { return [] }

// Note: Target doesn't have a directoryURL counterpart to directory,
// so we cannot eliminate this deprecation warning.
let sourceDir = target.directory.string

// Read a configuration file JavaKit.config from the target that provides
// information needed to call Java2Swift.
let configFile = URL(filePath: sourceDir)
.appending(path: "Java2Swift.config")
let configData = try Data(contentsOf: configFile)
let config = try JSONDecoder().decode(Configuration.self, from: configData)

/// Find the manifest files from other Java2Swift executions in any targets
/// this target depends on.
var manifestFiles: [URL] = []
func searchForManifestFiles(in target: any Target) {
let dependencyURL = URL(filePath: target.directory.string)

// Look for a checked-in manifest file.
let generatedManifestURL = dependencyURL
.appending(path: "generated")
.appending(path: "\(target.name).swift2java")
let generatedManifestString = generatedManifestURL
.path(percentEncoded: false)

if FileManager.default.fileExists(atPath: generatedManifestString) {
manifestFiles.append(generatedManifestURL)
}

// TODO: Look for a manifest file that was built by the plugin itself.
}

// Process direct dependencies of this target.
for dependency in target.dependencies {
switch dependency {
case .target(let target):
searchForManifestFiles(in: target)

case .product(let product):
for target in product.targets {
searchForManifestFiles(in: target)
}

@unknown default:
break
}
}

// Process indirect target dependencies.
for dependency in target.recursiveTargetDependencies {
searchForManifestFiles(in: dependency)
}

/// Determine the list of Java classes that will be translated into Swift,
/// along with the names of the corresponding Swift types. This will be
/// passed along to the Java2Swift tool.
let classes = config.classes.map { (javaClassName, swiftName) in
(javaClassName, swiftName ?? javaClassName.defaultSwiftNameForJavaClass)
}.sorted { (lhs, rhs) in
lhs.0 < rhs.0
}

let outputDirectory = context.pluginWorkDirectoryURL
.appending(path: "generated")

var arguments: [String] = [
"--module-name", sourceModule.name,
"--output-directory", outputDirectory.path(percentEncoded: false),
]
if let classPath = config.classPath {
arguments += ["-cp", classPath]
}
arguments += manifestFiles.flatMap { manifestFile in
[ "--manifests", manifestFile.path(percentEncoded: false) ]
}
arguments += classes.map { (javaClassName, swiftName) in
"\(javaClassName)=\(swiftName)"
}

/// Determine the set of Swift files that will be emitted by the Java2Swift
/// tool.
let outputSwiftFiles = classes.map { (javaClassName, swiftName) in
outputDirectory.appending(path: "\(swiftName).swift")
} + [
outputDirectory.appending(path: "\(sourceModule.name).swift2java")
]

return [
.buildCommand(
displayName: "Wrapping \(classes.count) Java classes target \(sourceModule.name) in Swift",
executable: try context.tool(named: "Java2Swift").url,
arguments: arguments,
inputFiles: [ configFile ],
outputFiles: outputSwiftFiles
)
]
}
}

// Note: the JAVA_HOME environment variable must be set to point to where
// Java is installed, e.g.,
// Library/Java/JavaVirtualMachines/openjdk-21.jdk/Contents/Home.
func findJavaHome() -> String {
if let home = ProcessInfo.processInfo.environment["JAVA_HOME"] {
return home
}

// This is a workaround for envs (some IDEs) which have trouble with
// picking up env variables during the build process
let path = "\(FileManager.default.homeDirectoryForCurrentUser.path()).java_home"
if let home = try? String(contentsOfFile: path, encoding: .utf8) {
if let lastChar = home.last, lastChar.isNewline {
return String(home.dropLast())
}

return home
}

fatalError("Please set the JAVA_HOME environment variable to point to where Java is installed.")
}

extension String {
/// For a String that's of the form java.util.Vector, return the "Vector"
/// part.
fileprivate var defaultSwiftNameForJavaClass: String {
if let dotLoc = lastIndex(of: ".") {
let afterDot = index(after: dotLoc)
return String(self[afterDot...])
}

return self
}
}
6 changes: 4 additions & 2 deletions Samples/JavaKitSampleApp/Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,16 @@ let package = Package(
.target(
name: "JavaKitExample",
dependencies: [
.product(name: "JavaKit", package: "swift-java")
.product(name: "JavaKit", package: "swift-java"),
.product(name: "JavaKitJar", package: "swift-java"),
],
swiftSettings: [
.swiftLanguageMode(.v5)
],
plugins: [
.plugin(name: "Java2SwiftPlugin", package: "swift-java"),
.plugin(name: "JavaCompilerPlugin", package: "swift-java")
]
),
]
)
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"classes" : {
"java.util.Vector" : null
Copy link
Collaborator

@ktoso ktoso Oct 15, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Vector is a rarely used type that folks generally avoid as it predates the "proper collections framework", I'd recommend avoiding it in examples (it'll look weird to Java developers that we're using that anywhere) and using java.util.ArrayList in examples.


double checked in docs:

As of the Java 2 platform v1.2, this class was retrofitted to implement the List interface, making it a member of the Java Collections Framework. Unlike the new collection implementations, Vector is synchronized. If a thread-safe implementation is not needed, it is recommended to use ArrayList in place of Vector.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was picking something silly that we wouldn't actually end up wrapping in any of the JavaKit* modules, but yeah... Vector is extra silly. Thanks for the ArrayList suggestion.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, no harm but a bit too silly maybe :) No prob

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
//===----------------------------------------------------------------------===//

import JavaKit
import JavaRuntime

enum SwiftWrappedError: Error {
case message(String)
Expand Down Expand Up @@ -118,3 +117,8 @@ struct HelloSubclass {
@JavaMethod
init(greeting: String, environment: JNIEnvironment)
}


func returnNilVector() -> Vector<JavaClass<HelloSwift>>? {
nil
}
Loading