Skip to content

[JExtract/JNI] Add support for primitive non-escaping closures. #327

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 5 commits into from
Jul 22, 2025
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
31 changes: 31 additions & 0 deletions Samples/JExtractJNISampleApp/Sources/MySwiftLibrary/Closures.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2025 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
//
//===----------------------------------------------------------------------===//

public func emptyClosure(closure: () -> ()) {
closure()
}

public func closureWithInt(input: Int64, closure: (Int64) -> Int64) -> Int64 {
return closure(input)
}

public func closureMultipleArguments(
input1: Int64,
input2: Int64,
closure: (Int64, Int64) -> Int64
) -> Int64 {
return closure(input1, input2)
}


Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//

package com.example.swift;

import org.junit.jupiter.api.Test;

import java.util.concurrent.atomic.AtomicBoolean;

import static org.junit.jupiter.api.Assertions.*;

public class ClosuresTest {
@Test
void emptyClosure() {
AtomicBoolean closureCalled = new AtomicBoolean(false);
MySwiftLibrary.emptyClosure(() -> {
closureCalled.set(true);
});
assertTrue(closureCalled.get());
}

@Test
void closureWithInt() {
long result = MySwiftLibrary.closureWithInt(10, (value) -> value * 2);
assertEquals(20, result);
}

@Test
void closureMultipleArguments() {
long result = MySwiftLibrary.closureMultipleArguments(5, 10, (a, b) -> a + b);
assertEquals(15, result);
}
}
23 changes: 12 additions & 11 deletions Sources/JExtractSwiftLib/Convenience/JavaType+Extensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,22 @@ import JavaTypes
extension JavaType {
var jniTypeSignature: String {
switch self {
case .boolean: "Z"
case .byte: "B"
case .char: "C"
case .short: "S"
case .int: "I"
case .long: "J"
case .float: "F"
case .double: "D"
case .boolean: return "Z"
case .byte: return "B"
case .char: return "C"
case .short: return "S"
case .int: return "I"
case .long: return "J"
case .float: return "F"
case .double: return "D"
case .class(let package, let name):
let nameWithInnerClasses = name.replacingOccurrences(of: ".", with: "$")
if let package {
"L\(package.replacingOccurrences(of: ".", with: "/"))/\(name);"
return "L\(package.replacingOccurrences(of: ".", with: "/"))/\(nameWithInnerClasses);"
} else {
"L\(name);"
return "L\(nameWithInnerClasses);"
}
case .array(let javaType): "[\(javaType.jniTypeSignature)"
case .array(let javaType): return "[\(javaType.jniTypeSignature)"
case .void: fatalError("There is no type signature for 'void'")
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,12 +76,12 @@ extension JNISwift2JavaGenerator {

for decl in analysis.importedGlobalFuncs {
self.logger.trace("Print global function: \(decl)")
printFunctionBinding(&printer, decl)
printFunctionDowncallMethods(&printer, decl)
printer.println()
}

for decl in analysis.importedGlobalVariables {
printFunctionBinding(&printer, decl)
printFunctionDowncallMethods(&printer, decl)
printer.println()
}
}
Expand Down Expand Up @@ -117,17 +117,17 @@ extension JNISwift2JavaGenerator {
printer.println()

for initializer in decl.initializers {
printFunctionBinding(&printer, initializer)
printFunctionDowncallMethods(&printer, initializer)
printer.println()
}

for method in decl.methods {
printFunctionBinding(&printer, method)
printFunctionDowncallMethods(&printer, method)
printer.println()
}

for variable in decl.variables {
printFunctionBinding(&printer, variable)
printFunctionDowncallMethods(&printer, variable)
printer.println()
}

Expand Down Expand Up @@ -175,12 +175,67 @@ extension JNISwift2JavaGenerator {
}
}

private func printFunctionBinding(_ printer: inout CodePrinter, _ decl: ImportedFunc) {
guard let translatedDecl = translatedDecl(for: decl) else {
private func printFunctionDowncallMethods(
_ printer: inout CodePrinter,
_ decl: ImportedFunc
) {
guard translatedDecl(for: decl) != nil else {
// Failed to translate. Skip.
return
}

printer.printSeparator(decl.displayName)

printJavaBindingWrapperHelperClass(&printer, decl)

printJavaBindingWrapperMethod(&printer, decl)
}

/// Print the helper type container for a user-facing Java API.
///
/// * User-facing functional interfaces.
private func printJavaBindingWrapperHelperClass(
_ printer: inout CodePrinter,
_ decl: ImportedFunc
) {
let translated = self.translatedDecl(for: decl)!
if translated.functionTypes.isEmpty {
return
}

printer.printBraceBlock(
"""
public static class \(translated.name)
"""
) { printer in
for functionType in translated.functionTypes {
printJavaBindingWrapperFunctionTypeHelper(&printer, functionType)
}
}
}

/// Print "wrapper" functional interface representing a Swift closure type.
func printJavaBindingWrapperFunctionTypeHelper(
_ printer: inout CodePrinter,
_ functionType: TranslatedFunctionType
) {
let apiParams = functionType.parameters.map(\.parameter.asParameter)

printer.print(
"""
@FunctionalInterface
public interface \(functionType.name) {
\(functionType.result.javaType) apply(\(apiParams.joined(separator: ", ")));
}
"""
)
}

private func printJavaBindingWrapperMethod(_ printer: inout CodePrinter, _ decl: ImportedFunc) {
guard let translatedDecl = translatedDecl(for: decl) else {
fatalError("Decl was not translated, \(decl)")
}

var modifiers = ["public"]
if decl.isStatic || decl.isInitializer || !decl.hasParent {
modifiers.append("static")
Expand Down Expand Up @@ -215,7 +270,7 @@ extension JNISwift2JavaGenerator {
if let selfParameter = nativeSignature.selfParameter {
parameters.append(selfParameter)
}
let renderedParameters = parameters.map { "\($0.javaParameter.type) \($0.javaParameter.name)"}.joined(separator: ", ")
let renderedParameters = parameters.map { "\($0.javaType) \($0.name)"}.joined(separator: ", ")

printer.print("private static native \(resultType) \(translatedDecl.nativeFunctionName)(\(renderedParameters));")
}
Expand Down
Loading
Loading