Skip to content

Add a SwiftPM build plugin to generate Swift wrappers for Java classes #77

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
1 change: 1 addition & 0 deletions .licenseignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
.swift-format
.github/*
*.md
**/*.config
Copy link
Collaborator

Choose a reason for hiding this comment

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

This is to fix the license checking CI job, since it checked and failed on the new file not having a license header

Copy link
Member Author

Choose a reason for hiding this comment

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

Ah, thank you!

CONTRIBUTORS.txt
LICENSE.txt
NOTICE.txt
Expand Down
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"]
),

.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.ArrayList" : "ArrayList"
}
}
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,10 @@ struct HelloSubclass {
@JavaMethod
init(greeting: String, environment: JNIEnvironment)
}


func removeLast(arrayList: ArrayList<JavaClass<HelloSwift>>) {
if let lastObject = arrayList.getLast() {
_ = arrayList.remove(lastObject)
}
}